C# 操作mongodb子文档

时间:2023-12-05 15:14:38
           var mongoString = "mongodb://jamesbing:123456@localhost: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 = },
new AddressItem {Add = "美国", Id = ObjectId.GenerateNewId(), Age = }
}
};
// var addresult = TMongodbHelper.Add(host, person);
var collection = TMongodbHelper.GetMongoCollection<Person>(host.ConnectionString, host.DatabaseName, host.CollectionName); //Update ChildDocument
var address = "Address.$";
var result = collection.Update(
Query.And(new List<IMongoQuery>
{
Query.EQ("_id", new ObjectId("577b344a87aebb23c0fc767a")),
Query.EQ("Address._id", new ObjectId("577b344a87aebb23c0fc767b")),
}), Update.Set(address + ".Age", )); //Add ChildDocument
//单个
var result2 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415")
), Update.Push("Address", new AddressItem { Add = "山西省运城市", Id = ObjectId.GenerateNewId() }.ToBsonDocument())); //多个
var result3 = collection.Update(Query.EQ("_id", new ObjectId("577b262587aebb41fca9a3af")
), Update.PushEach("Address", new[] { new AddressItem { Add = "山西省运城市4", Id = ObjectId.GenerateNewId(), Age = }.ToBsonDocument(), new AddressItem { Add = "山西省运城市5", Id = ObjectId.GenerateNewId(), Age = }.ToBsonDocument() })); //Remove ChildDocument
var result4 = collection.Update(Query.EQ("_id", new ObjectId("577b2d6787aebb198839d415")),
Update.Pull("Address", new { Id = new ObjectId("577b2d9387aebb2d7449367f") }.ToBsonDocument())); //Query ChildDocument
  var query = Query.EQ("_id", new ObjectId("577b30e087aebb34ec170e7a"));
             var q = Query.ElemMatch("Address"", Query.EQ("Add", "北京市"));     
            var result5= collection.FindOne(Query.And(query,q));

备注:

mongodb for C# SDK版本:1.11(可支持mongodb 3.2版本)

mongodb版本:3.0.6