Mongodb C# 批量更新/替换子集合 [英] Mongodb C# bulk update/replace on subcollection
问题描述
给出以下对象结构:
public class RootDocument
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public List<ChildDocument> Documents { get; set; }
}
public class ChildDocument
{
public Guid Id { get; set; }
public string Name { get; set; }
public string SomeProperty { get; set; }
}
我想更新 RootDocument
集合中所有 RootDocument
上指定 Id
的所有 ChildDocuments
.
I want to update all ChildDocuments
of a specified Id
on all RootDocument
in a RootDocument
collection.
我们的想法是在这样的批量操作中更新它们:
The idea is to update them all in a bulk operation like this:
var document = new ChildDocument() { Id = <id of existing ChildDocument>, Name = ..., ...);
var bulkOperations = new WriteModel<RootDocument>[]
{
new UpdateManyModel<RootDocument>(
Builders<RootDocument>.Filter.Eq("Documents.Id", document.id),
Builders<RootDocument>.Update.AddToSet(x => x.Documents, document))
};
await mongoDatabase.GetCollection<RootDocument>()
.BulkWriteAsync(bulkOperations, new BulkWriteOptions { IsOrdered = false });
但是AddToSet
不是现有ChildDocument
的替换操作.
But AddToSet
is not a replace operation of the existing ChildDocument
.
使用最新的 MongoDB C# 驱动程序实现此要求的最佳方法是什么?
What is the best way with the latest MongoDB C# driver to implement this requirement?
推荐答案
阅读 位置运算符.在这种情况下,您不需要批量,只需 UpdateMany.
Have a read of the positional operator. In this case, you don't need bulk, just UpdateMany.
collection.UpdateMany(
Builders<RootDocument>.Filter.Eq("Documents.Id", document.Id),
Builders<RootDocument>.Update.Set("Documents.$", document));
这将遍历集合并匹配具有指定 Id 的 ChildDocument 的任何 RootDocument,然后将其替换为提供的文档.
This will go through the collection and match any RootDocument who has a ChildDocument with the specified Id and subsequently replace it with the provided document.
这篇关于Mongodb C# 批量更新/替换子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!