netcore 使用mongodb
docker 安装mongodb:docker pull mongo
运行容器
新建项目Contact.Api 实现一个简易的联系人列表
nuget引用包MongoDB.Driver
添加配置文件
"ConnectionStrings": { "ConnectionString": "mongodb://localhost:27017", "Database": "Finbook_Contacts", "LogCollection": "Finbook_Contacts_log" }
添加数据库配置
/// <summary> /// 数据库配置信息 /// </summary> public class DBSettings { /// <summary> /// mongodb connectionstring /// </summary> public string ConnectionString { get; set; } /// <summary> /// mongodb database /// </summary> public string Database { get; set; } /// <summary> /// 日志collection /// </summary> public string LogCollection { get; set; } }
添加db上下文
public class ContactContext { private IMongoDatabase _dataBase; private readonly string _logCollection; public ContactContext(IOptions<DBSettings> settings) { var client = new MongoClient(settings.Value.ConnectionString); if (client != null) _dataBase = client.GetDatabase(settings.Value.Database); _logCollection = settings.Value.LogCollection; } private void CheckAddCreateCollection(string collectionName) { var collectionList = _dataBase.ListCollections().ToList(); var collectionNames = new List<string>(); //获得所有集合的名称 collectionList.ForEach(x => { collectionNames.Add(x["name"].AsString); }); //如果没有这个集合就创建一个 (相当于创建一个表) if (!collectionNames.Contains(collectionName)) { _dataBase.CreateCollection(collectionName); } } public IMongoCollection<LogEventData> LogEventDatas { get { CheckAddCreateCollection(_logCollection); return _dataBase.GetCollection<LogEventData>(_logCollection); } } public IMongoCollection<ContactBook> ContactBooks { get { CheckAddCreateCollection("ContactBooks"); return _dataBase.GetCollection<ContactBook>("ContactBooks"); } } public IMongoCollection<T> GetCollection<T>(string name) where T : class { CheckAddCreateCollection(name); return _dataBase.GetCollection<T>(name); } public IMongoCollection<ContactApplyRequest>ContactApplyRequests { get { CheckAddCreateCollection("ContactApplyRequests"); return _dataBase.GetCollection<ContactApplyRequest>("ContactApplyRequests"); } } }