1. 程式人生 > >Asp.net Core 2.1使用MongoDB

Asp.net Core 2.1使用MongoDB

一、新增依賴

1、MongoDB.Driver

2、MongoDB.Bson

二、配置服務到StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
 //新增mongodb依賴
 string mongoConnectionString = Configuration.GetSection("Mongo:ConnectionString").Value;
 services.AddSingleton(new MongoClient(mongoConnectionString));
}

三、新增配置到appsettings.json

{
  "Mongo": {
    "ConnectionString": "mongodb://賬號:密碼@伺服器IP:27017/預設資料庫名稱"
  }
}

四、自己編寫的一個幫助類;這裡只公佈一部分。 其餘的可以自行拓展

public class MongoBase<T>: IMongoBase<T> //介面可自己根據此類抽象出來
    {

        private IMongoCollection<T> mongoClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="name">MongoDB的表名</param>
        public MongoBase(MongoClient client, string name)
        {
            var database = client.GetDatabase("資料庫名稱");
            mongoClient = database.GetCollection<T>(name);
        }

        #region 新增單個 + void InsertOne(T entity)
        /// <summary>
        /// 新增單個
        /// </summary>
        /// <param name="entity"></param>
        public void InsertOne(T entity)
        {
            mongoClient.InsertOne(entity);
        }
        #endregion

        #region 批量新增 + void InsertMany(IEnumerable<T> entity)
        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="entity"></param>
        public void InsertMany(IEnumerable<T> entity)
        {
            mongoClient.InsertMany(entity);
        }
        #endregion

        #region 查詢第一個 + T FindFirst(FilterDefinition<T> filter,FindOptions option =  null)
        /// <summary>
        /// 查詢第一個
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public T FindFirst(FilterDefinition<T> filter, FindOptions option = null)
        {
            return mongoClient.Find(filter, option).FirstOrDefault();
        }
        #endregion

        #region 查詢多個 + List<T> FindList(FilterDefinition<T> filter, FindOptions option = null)
        /// <summary>
        /// 查詢多個
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public List<T> FindList(FilterDefinition<T> filter, FindOptions option = null)
        {
            return mongoClient.Find(filter, option).ToList();
        }
        #endregion

    }

五、編寫一個MongoDB集合;

這裡使用一個叫UserInfo的MongoDB資料庫集合做測試

    public class UserInfoService : MongoBase<UserInfo>
    {
        public UserInfoService(MongoClient client) : base(client, "UserInfo")
        { }

    }

六、在Controller中使用

    public class MongoController : Controller
    {
        private UserInfoService userInfo;
        //使用DI注入;
        public MongoController(UserInfoService _userInfo)
        {
            this.userInfo = _userInfo;
        }
        public IActionResult Index()
        {
            UserInfo user = userInfo.FindFirst(Builders<UserInfo>.Filter.Eq(p => p.Name, "Test"));
            userInfo.InsertOne(new UserInfo() { Name="Test", UserID=222 });

            user = userInfo.FindFirst(Builders<UserInfo>.Filter.Eq(p => p.Name, "Test"));
            return View();
        }
    }