netcore 使用mongodb

docker 安装mongodb:docker pull mongo
运行容器

docker run -d -p 27017:27017 --name mongo01 -v /docker/mongo/config:/data/configdb -v /docker/mongo/db:/data/db mongo

进入容器.

docker exec -it mongodb bash

 创建用户

# 进入 admin 的数据库

use admin

# 创建管理员用户

db.createUser(

{

user: "admin",

pwd: "123456",

roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

}

)

# 创建有可读写权限的用户. 对于一个特定的数据库, 比如'demo'

db.createUser({

user: 'test',

pwd: '123456',

roles: [{role: "read", db: "demo"}]

})

 

新建项目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");
            }
        }
    }

 

posted @ 2019-11-06 10:54  煤炭g  阅读(629)  评论(0编辑  收藏  举报