zoukankan      html  css  js  c++  java
  • .net core连接mongoDB

     配置文件

    {
    "ConnectionStrings": {
    "ConnectionString": "mongodb://admin:123456@192.168.1.6:27017",
    "DatabaseName": "testdb"
    }
    }

     首先引用包

    <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.2" />
    <PackageReference Include="MongoDB.Driver" Version="2.10.2" />

    CRUD 操作服务

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Extensions.Configuration;
    using MongoDB.Driver;
    
    namespace MongoDbTestConsoleApp
    {
        /// <summary>
        /// 官方 https://api.mongodb.com/csharp/2.2/html/R_Project_CSharpDriverDocs.htm
        ///  https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-3.1&tabs=visual-studio
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class BaseRepository<T> where T : BaseModel
        {
            private readonly IMongoCollection<T> _collection;   //数据表操作对象
    
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="config"></param>
            /// <param name="tableName">表名</param>
            public BaseRepository(DatabaseSettings config, string tableName)
            {
                var client = new MongoClient(config.ConnectionString);    //获取链接字符串
    
                var database = client.GetDatabase(config.DatabaseName);
    
                //var database = client.GetDatabase(config.GetSection("MongoDBSetting:DBName").Value);   //数据库名 (不存在自动创建)
    
                //获取对特定数据表集合中的数据的访问
                _collection = database.GetCollection<T>(tableName);     // (不存在自动创建)
            }
    
            //Find<T> – 返回集合中与提供的搜索条件匹配的所有文档。
            //InsertOne – 插入提供的对象作为集合中的新文档。
            //ReplaceOne – 将与提供的搜索条件匹配的单个文档替换为提供的对象。
            //DeleteOne – 删除与提供的搜索条件匹配的单个文档。
    
            /// <summary>
            /// 获取所有
            /// </summary>
            /// <returns></returns>
            public List<T> Get()
            {
                return _collection.Find(T => true).ToList();
            }
    
            /// <summary>
            /// 获取单个
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            public T Get(string id)
            {
                return _collection.Find<T>(T => T.Id == id).FirstOrDefault();
            }
    
            /// <summary>
            /// 创建
            /// </summary>
            /// <param name="T"></param>
            /// <returns></returns>
            public T Create(T T)
            {
                _collection.InsertOne(T);
                return T;
            }
    
            /// <summary>
            /// 更新
            /// </summary>
            /// <param name="id"></param>
            /// <param name="TIn"></param>
            public void Update(string id, T TIn)
            {
                _collection.ReplaceOne(T => T.Id == id, TIn);
            }
    
            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="TIn"></param>
            public void Remove(T TIn)
            {
                _collection.DeleteOne(T => T.Id == TIn.Id);
            }
    
            /// <summary>
            /// 根据id删除
            /// </summary>
            /// <param name="id"></param>
            public void Remove(string id)
            {
                _collection.DeleteOne(T => T.Id == id);
            }
        }
    }
    

      配置文件模型

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace MongoDbTestConsoleApp
    {
        public class DatabaseSettings
        {
            public string ConnectionString { get; set; }
            public string DatabaseName { get; set; }
        }
    }
    

      基础实体模型

    using System;
    using System.Collections.Generic;
    using System.Text;
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    
    namespace MongoDbTestConsoleApp
    {
        public class BaseModel
        {
            [BsonId]        //标记主键
            [BsonRepresentation(BsonType.ObjectId)]     //参数类型  , 无需赋值
            public string Id { get; set; }
    
            [BsonElement(nameof(AddTime))]   //指明数据库中字段名为CreateDateTime
            public DateTime AddTime { get; set; }
    
            [BsonElement(nameof(IsDelete))]
            public bool IsDelete { get; set; }
    
            public BaseModel()
            {
                AddTime = DateTime.Now;
                IsDelete = false;
            }
        }
    }
    

      测试模型

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace MongoDbTestConsoleApp
    {
        public class StudentModel:BaseModel
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    

      另外关于mongodb想直接使用BsonDocument序列化

    直接tojson是数据类型是有包装的 例如ObjectId 是ObjectId("5e5e71be0036020790ea4058")

    如果想将mongodb的ObjectId转换成正常的json格式

    {
            "_id" : ObjectId("5e5e71be0036020790ea4058"),
            "Name" : "test"
    }
    

      

    {"_id":"5e58c528fbaf8aa66a11cfd9","name":"菜鸟教程"}
    

      或则

    { "_id" : { "$oid" : "5e58c528fbaf8aa66a11cfd9" }, "name" : "菜鸟教程" }
    

      具体代码如下 可以看到区别

                var testconl = mycol.Find(x => true).ToList();
    
                JsonWriterSettings jsonWriterSettings = new JsonWriterSettings();
                jsonWriterSettings.OutputMode = JsonOutputMode.Strict;
    
                foreach (var item in testconl)
                {
                    var bsonType = item.BsonType;
                    var dic = new Dictionary<string, object> { };
                    foreach (var ele in item.Elements)
                    {
                        
                        if (ele.Value is BsonObjectId)
                        {
                            var vid =new BsonString(ele.Value.ToString());
                            //item.Remove(ele.Name);
                            //item.Add(new BsonElement(ele.Name, vid));
                            dic.Add(ele.Name, ele.Value.ToString());
                        }
                        else
                        {
                            dic.Add(ele.Name, ele.Value);
                        }
    
                    }
                    Console.WriteLine(item.ToJson());
                    Console.WriteLine(item.ToJson(jsonWriterSettings));
                    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(dic));
                }
    

      

  • 相关阅读:
    二十八 .Django中模型类中Meta元对象了解
    【POJ2376】Cleaning Shifts
    【CF600E】Lomsat gelral
    【hiho1035】自驾旅行III
    【模板】manachar
    【hiho1065】全图传送
    【洛谷P1450】硬币购物
    【HDU2204】Eddy's爱好
    【CF208E】Blood Cousins
    【CF451E】Devu and Flowers
  • 原文地址:https://www.cnblogs.com/wangboy91/p/12405500.html
Copyright © 2011-2022 走看看