标签:
1 var mongoString = "mongodb://jamesbing:123456@localhost:27017"; 2 var host = new TMongodbHostModel 3 { 4 CollectionName = "ft_test", 5 ConnectionString = mongoString, 6 DatabaseName = "system_db" 7 }; 8 9 var person = new Person 10 { 11 Id = ObjectId.GenerateNewId(), 12 Name = "jamesbing", 13 Address = new List<AddressItem> 14 { 15 new AddressItem {Add = "英国", Id = ObjectId.GenerateNewId(), Age = 12}, 16 new AddressItem {Add = "美国", Id = ObjectId.GenerateNewId(), Age = 19} 17 } 18 }; 19 // var addresult = TMongodbHelper.Add(host, person); 20 var collection = TMongodbHelper.GetMongoCollection<Person>(host.ConnectionString, host.DatabaseName, host.CollectionName); 21 22 //Update ChildDocument 23 var address = "Address.$"; 24 var result = collection.Update( 25 Query.And(new List<IMongoQuery> 26 { 27 Query.EQ("_id", new ObjectId("577b344a87aebb23c0fc767a")), 28 Query.EQ("Address._id", new ObjectId("577b344a87aebb23c0fc767b")), 29 }), Update.Set(address + ".Age", 33)); 30 31 32 //Add ChildDocument 33 //单个 34 var result2 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415") 35 ), Update.Push("Address", new AddressItem { Add = "山西省运城市", Id = ObjectId.GenerateNewId() }.ToBsonDocument())); 36 37 //多个 38 var result3 = collection.Update(Query.EQ("_id", new ObjectId("577b262587aebb41fca9a3af") 39 ), Update.PushEach("Address", new[] { new AddressItem { Add = "山西省运城市4", Id = ObjectId.GenerateNewId(), Age = 10 }.ToBsonDocument(), new AddressItem { Add = "山西省运城市5", Id = ObjectId.GenerateNewId(), Age = 9 }.ToBsonDocument() })); 40 41 //Remove ChildDocument 42 var result4 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415")), 43 Update.Pull("Address", new { Id = new ObjectId("577b2d9387aebb2d7449367f") }.ToBsonDocument())); 44 45 46 //Query ChildDocument 47 var q = Query.And(new[] 48 {Query.EQ("_id", new ObjectId("577b30e087aebb34ec170e7a")), Query.EQ("Add", "北京市")}); 49 var qresult = collection.Find(Query.ElemMatch("Address", q)).FirstOrDefault(); 50 Console.ReadKey();
备注:
mongodb for C# SDK版本:1.10
mongodb版本:3.0.6
标签:
原文地址:http://www.cnblogs.com/gaobing/p/5667021.html