前提說明: 本編文章所屬的微服務框架代碼和對mongo支持的代碼全部放在github,地址:https://github.com/PeyShine/Demo.MicroServer 另外,如果不知道怎麼安裝mongodb可以看這篇:https://www.cnblogs.com/peyshine/p ...
前提說明:
本編文章所屬的微服務框架代碼和對mongo支持的代碼全部放在github,地址:https://github.com/PeyShine/Demo.MicroServer 另外,如果不知道怎麼安裝mongodb可以看這篇:https://www.cnblogs.com/peyshine/p/12876471.html 1.在數據倉儲層Demo.MicroServer.Repository,添加Mongo依賴包:dotnet add package MongoDB.Driver 2.編寫mongo常用的一些介面以及介面的實現,後續可以根據實際開發情況再進行更多介面的封裝


services.AddTransient(typeof(IMongoService), typeof(MongoService));
4.編寫與mongoDB交互的測試介面
/// <summary> /// 測試從mongodb中獲取用戶數量 /// </summary> /// <returns></returns> [HttpGet] public async Task<long> GetMongoUserCount() { var list = new List<FilterDefinition<user_mongo>>(); list.Add(Builders<user_mongo>.Filter.Exists("user_id", true)); var filter = Builders<user_mongo>.Filter.And(list); return await _mongoService.CountAsync(filter, "users"); }
5.在mongo中準備兩條測試數據
6.在swagger中調用介面來測試
最後看到輸出結果為數量為2,和添加的數量一致。