使用Mongo C#2.0驱动程序替换嵌入式文档 [英] Replace Embedded Document using Mongo C# 2.0 driver
本文介绍了使用Mongo C#2.0驱动程序替换嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含嵌入式单元阵列的文档,如下所示:
I have a document that have a embedded array of units, like this:
{
"_id" : ObjectId("5807c22e959ca231f0c48a75"),
"Code" : "Value",
"Units" : [
{
"_id" : ObjectId("5807cc08959ca331f09c530e"),
"Code" : "Foo",
"Label" : "Foo"
},
{
"_id" : ObjectId("5807cc08959ca331f09c530e"),
"Code" : "Bar",
"Label" : "Bar"
},
]
}
我想通过其ID查找一个单位,并将其替换为新文档. 我该如何使用Mongo C#驱动程序2.0做到这一点?
I want to find a unit by its id and replace it with a new document. How could I do that using the Mongo C# Driver 2.0?
提前谢谢!
推荐答案
谢谢大家.根据您的回答,我提出了以下解决方案:
Thanks guys. From your answers, I came up with the following solution:
var mainDocumentId = "5807c22e959ca231f0c48a75";
var arrayItemId = "5807cc08959ca331f09c530e"; //Id for foo
var unit = new Unit(...)
var filter = Builders<UnitType>.Eq(o => o.Id, mainDocumentId); // optional
filter &= Builders<UnitType>.Filter.ElemMatch(o => o.Units, o => o.Id == arrayItemId);
var update = Builders<UnitType>.Update.Set(o => o.Units[-1], unit);
collection.UpdateOne(filter, update);
这篇关于使用Mongo C#2.0驱动程序替换嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文