数组存储是Mongodb的一个非常遍历的地方,可以不用存储上下文关联关系,直接级联删除。本文这里简单的介绍下数组的用法:
数据:
var record = new
{
Id = “t1”,
Name = “tt1”,
SubTypes = new object[]
{
new {Id = “s1”, Value = “11”},
new {Id = “s2”, Value = “l22”},
}
};
table.InsertOne(record.ToBsonDocument());
插入:
var filter = new {Id = “t1”}.ToBsonDocument();
var push = Builders<BsonDocument>.Update.Push(“SubTypes”, new { Id = “s3”, Value = “333” });
table.UpdateOne(filter, push);
删除:
var filter = new {Id = “t1”}.ToBsonDocument();
var pull = Builders<BsonDocument>.Update.Pull(“SubTypes”, new { Id = “s2” });
table.UpdateOne(filter, pull);
更新:
更新则要复杂些:
var filter = new BsonDocument()
{
[“_id”] = “t1”,
[“SubTypes._id”] = “s1”
};
var set = Builders<BsonDocument>.Update.Set(“SubTypes.$.Value”, “v3”);
table.UpdateOne(filter, set);
参考文档:
https://docs.mongodb.com/manual/reference/operator/update-array/
原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/273460.html