ASP.NET Core3.1 中使用MongoDB基本操作

1、安装驱动包

  

install-package  MongoDB.Driver -version 2.11.7

 

2、配置文件帮助类 ConfigHelper

 

 public static class ConfigHelper
    {
        private static IConfiguration _configuration;

        static ConfigHelper()
        {
            //在当前目录或者根目录中寻找appsettings.json文件
            string fileName = "appsettings.json";

            string directory = AppContext.BaseDirectory;
            directory = directory.Replace("\\", "/");

            string filePath = $"{directory}/{fileName}";
            if (!File.Exists(filePath))
            {
                var length = directory.IndexOf("/bin");
                filePath = $"{directory.Substring(0, length)}/{fileName}";
            }

            var builder = new ConfigurationBuilder().AddJsonFile(filePath, false, true);
            _configuration = builder.Build();

        }

        public static string GetSectionValue(string key)
        {
            return _configuration.GetSection(key).Value;
        }

    }

 

 

3、appsettings.json配置

 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "MongoDBAddress": "mongodb://192.168.0.161:27017", //连接字符串
  "MongoDBName": "local" //集合名
}

 

 

4、实体类

 

    /// <summary>
    /// 公共实体类
    /// </summary>
    public class BaseModel
    {
        [BsonId]        //标记主键
        [BsonRepresentation(BsonType.ObjectId)]     //参数类型  , 无需赋值
        public string Id { get; set; }

        [BsonElement(nameof(CreateDateTime))]   //指明数据库中字段名为CreateDateTime
        public DateTime CreateDateTime { get; set; }

        //[BsonElement(nameof(IsDelete))]
        public bool IsDelete { get; set; }

        public BaseModel()
        {
            CreateDateTime = DateTime.Now;
            IsDelete = false;
        }
    }

 


namespace MongodbDemo.Models
{

  public class Student : BaseModel
  {

     public string Name { get; set; }
     public int Age { get; set; }

     List<Course> _courses = new List<Course>();
     public virtual List<Course> Courses { get { return _courses; } set { _courses = value; } }
  }

  public class Course
  {

     public string StudentId { get; set; }
     public string Name { get; set; }

  }

 

}

 

5、业务基础类

namespace MongodbDemo.Services
{
    /// <summary>
    /// 业务基础类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseMongoDbService<T> where T : BaseModel
    {
        protected readonly IMongoCollection<T> _collection;   //数据表操作对象

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tableName">表名</param>
        public BaseMongoDbService(string tableName)
        {
            var client = new MongoClient(ConfigHelper.GetSectionValue("MongoDBAddress"));    //获取链接字符串
            var database = client.GetDatabase(ConfigHelper.GetSectionValue("MongoDBName"));   //数据库名 (不存在自动创建)
            _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 Add(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>
        /// 根据id删除
        /// </summary>
        /// <param name="id"></param>
        public void Remove(string id)
        {
            _collection.DeleteOne(T => T.Id == id);
        }
    }
}

 

6、调用方式

      StudentService _studentService = new StudentService();
        public void Test()
        {

            Student _students = new Student();
            _students.Name = "张三";
            _students.Age = 10;
            Course _course = new Course();
            _course.StudentId = _students.Id;
            _course.Name = "数学";
            _students.Courses.Add(_course);
            _studentService.Add(_students);
       }

 

 

 

posted @ 2020-09-16 15:17  斌言  阅读(774)  评论(0编辑  收藏  举报