Search code examples
c#mongodbmongodb-.net-driverbulk-operations

Mongodb C# bulk update/replace on subcollection


The following object structure is given:

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; }
}

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 });

But AddToSet is not a replace operation of the existing ChildDocument.

What is the best way with the latest MongoDB C# driver to implement this requirement?


Solution

  • 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));
    

    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.