码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB 学习 5 组件 MongoDB.Driver,增删改

时间:2021-05-24 09:44:03      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:集合   属性   gui   serial   一个   worker   实体类   匹配   des   

使用组件 MongoDB.Driver

插入数据

    class Program
    {
        static void Main(string[] args)
        {
            AddWorkerToMongo();
        }


        static void AddWorkerToMongo()
        {
            var client = new MongoClient("mongodb://liuyi:123qweasd@127.0.0.1:27017");//有账号密码的这么写,没有的去掉liuyi:123qweasd@
            var db = client.GetDatabase("test");//选择库

            var dc = BsonDocument.Parse("{‘name‘:‘杨戬‘,‘age‘:6000,‘gender‘:‘男‘,‘salary‘:9999}");//Bson化JSON数据
            
            db.GetCollection<BsonDocument>("worker").InsertOne(dc);//选择集合worker,用InsertOne

        }
    }

这样的问题在于,写JSON格式的数据太麻烦了,容易出错,用实体类比较好

定义一个Worker的实体类

    [BsonDiscriminator("worker")]
    public class Worker
    {
        [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
        public string _id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
        [BsonElement("age")]
        public int age { get; set; }
        [BsonElement("gender")]
        public string gender { get; set; }
        [BsonElement("salary")]
        public decimal salary { get; set; }
    }

这里的属性都一一对应mongodb里文档的字段。

修改方法

        static void AddWorkerToMongo()
        {
            var client = new MongoClient("mongodb://liuyi:123qweasd@127.0.0.1:27017");//有账号密码的这么写,没有的去掉liuyi:123qweasd@
            var db = client.GetDatabase("test");//选择库

            //var dc = BsonDocument.Parse("{‘name‘:‘杨戬‘,‘age‘:6000,‘gender‘:‘男‘,‘salary‘:9999}");//Bson化JSON数据
            //Worker w = BsonSerializer.Deserialize<Worker>(dc);//将BSON格式数据转换成实体类对象

            Worker w = new Worker()
            {
                _id = Guid.NewGuid().ToString(),
                name = "太上老君",
                age = 994900,
                gender = "",
                salary = 999999
            };
            db.GetCollection<Worker>("worker").InsertOne(w);//选择集合worker,用InsertOne

        }

直接传对象,文档会根据传递的对象的类和指定的文档进行转换。

 

批量插入

        static void AddWorkersToMongo()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            List<Worker> workers = new List<Worker>() {
                new Worker(){
                     _id = Guid.NewGuid().ToString(),
                    name = "雷公",
                    age = 121210,
                    gender = "",
                    salary = 99999
                },
                new Worker(){
                    _id = Guid.NewGuid().ToString(),
                    name = "电母",
                    age = 121210,
                    gender = "",
                    salary = 9999
                 }
            };
            db.GetCollection<Worker>("worker").InsertMany(workers);
        }

 

带子文档的插入

修改worker类

    [BsonDiscriminator("worker")]
    public class Worker
    {
        [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
        public string _id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
        [BsonElement("age")]
        public int age { get; set; }
        [BsonElement("gender")]
        public string gender { get; set; }
        [BsonElement("salary")]
        public decimal salary { get; set; }

        [BsonElement("detailInfo")]
        public List<DetailInfo> detailInfo = new List<DetailInfo>();
    }

    public class DetailInfo
    {
        [BsonElement("country")]
        public string country { get; set; }
        [BsonElement("province")]
        public string province { get; set; }
        [BsonElement("city")]
        public string city { get; set; }
    }

这里就用单个插入,批量不改了

           Worker w = new Worker()
            {
                _id = Guid.NewGuid().ToString(),
                name = "雷震子",
                age = 452323,
                gender = "",
                salary = 55445,
                detailInfo = new List<DetailInfo>() {
                new DetailInfo(){
                    country="中国",
                    province = "湖南",
                    city="长沙"
                }
                }
            };
            db.GetCollection<Worker>("worker").InsertOne(w);//选择集合worker,用InsertOne        

 

删除数据

        static void DeleteWorkerFromMongo()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            FilterDefinitionBuilder<Worker> builder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = builder.Eq(doc => doc.name,"雷公");//过滤条件,name = 雷公的数据
            db.GetCollection<Worker>("worker").DeleteOne(filter);//只删除匹配的第一条 
        }

 

deleteOne删除第一条,deleteMany删除多条。

 

更新数据

普通更新

        static void UpdateWorkerToMongo()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            //过滤出要修改的文档
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = filterBuilder.Eq(doc => doc.name, "悟空");
            //设置文档要修改的内容
            UpdateDefinitionBuilder<Worker> updateBuilder = Builders<Worker>.Update;
            UpdateDefinition<Worker> update = updateBuilder.Set(doc => doc.age, 19291)
                .Set(doc => doc.salary, 18000);
            //只修改一条,多条用UpdateMany
            db.GetCollection<Worker>("worker").UpdateOne(filter, update);
        }

插入子文档

        static void UpdateWorkerToMongo2()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            //过滤出要修改的文档
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filter = filterBuilder.Eq(doc => doc.name, "雷震子");

            //设置文档要修改的内容
            UpdateDefinitionBuilder<Worker> updateBuilder = Builders<Worker>.Update;
            //用的PushEach方法,压入子文档内容
            UpdateDefinition<Worker> update = updateBuilder.PushEach(
                doc => doc.detailInfo, new List<DetailInfo> {
                 new DetailInfo(){
                    country="中国",
                    province="广东",
                    city="广州"
                 }
                }, null, 0, null);//这个0是位置,表示插入到list的哪个位置
            //只修改一条,多条用UpdateMany
            db.GetCollection<Worker>("worker").UpdateOne(filter, update);
        }

修改子文档,这个稍微麻烦些

        static void UpdateWorkerToMongo3()
        {
            var client = new MongoClient(conString);
            var db = client.GetDatabase(dbName);
            //过滤出要修改的文档
            //过滤父文档
            FilterDefinitionBuilder<Worker> filterBuilder = Builders<Worker>.Filter;
            FilterDefinition<Worker> filterFather = filterBuilder.Eq(doc => doc.name, "雷震子");
            //过滤子文档
            FilterDefinition<Worker> filterChild = filterBuilder.ElemMatch(
                list => list.detailInfo, child => child.country == "中国") &
                filterBuilder.ElemMatch(list => list.detailInfo, child => child.province == "广东");
            //合并过滤条件
            FilterDefinition<Worker> filter = Builders<Worker>.Filter.And(
                new FilterDefinition<Worker>[] { filterFather, filterChild });
            //设置文档要修改的内容
            UpdateDefinitionBuilder<Worker> updateBuilder = Builders<Worker>.Update;
            //Set,detailInfo.$.city定位到想改的字段
            UpdateDefinition<Worker> update = updateBuilder.Set("detailInfo.$.city", "深圳");
            //只修改一条,多条用UpdateMany
            var r = db.GetCollection<Worker>("worker").UpdateOne(filter, update);
        }

 

MongoDB 学习 5 组件 MongoDB.Driver,增删改

标签:集合   属性   gui   serial   一个   worker   实体类   匹配   des   

原文地址:https://www.cnblogs.com/luyShare/p/14769878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!