C# 更新Mongodb子文档的实现方法

参考资源:

  1:mongodb3.2系统性学习——3、update()操作

  2: C# 操作mongodb子文档

 

代码如下:

 var mongoString = "mongodb://xxxxxxxxxxx:27017";
             var host = new TMongodbHostModel
             {
                 CollectionName = "ft_test",
                 ConnectionString = mongoString,
                 DatabaseName = "system_db"
             };
 
             var person = new Person
             {
                 Id = ObjectId.GenerateNewId(),
                 Name = "jamesbing",
                 Address = new List<AddressItem>
                 {
                     new AddressItem {Add = "英国", Id = ObjectId.GenerateNewId(), Age = 12},
                     new AddressItem {Add = "美国", Id = ObjectId.GenerateNewId(), Age = 19}
                 }
             };
             var collection = TMongodbHelper.GetMongoCollection<Person>(host.ConnectionString, host.DatabaseName, host.CollectionName);
 
             //Update ChildDocument
             var address = "Address.$.{0}";
             var result = collection.FindAndModify(
                 Query.And(new List<IMongoQuery>
                 {
                    Query.EQ("_id", new ObjectId("577b344a87aebb23c0fc767a")),
                     Query.EQ("Address._id", new ObjectId("577b344a87aebb23c0fc767b")),
                 }), MongoDB.Driver.Builders.Update.Set(string.Format(address, "Age"), BsonValue.Create(33)));

 

posted @ 2017-08-01 11:53  王亚奇  阅读(492)  评论(0编辑  收藏  举报