This is perhaps one of the most common and basic database operations you can perform. However, how you perform this operation in MongoDb, is elusive.
There's a UpdateManyAsync
method in the C# driver. But all I can find for it is examples like;
The following operation updates all documents where violations are greater than 4 and $set a flag for review:
try {
db.restaurant.updateMany(
{ violations: { $gt: 4 } },
{ $set: { "Review" : true } }
);
} catch (e) {
print(e);
}
Frankly I don't know how you guys build your applications but our organization will never embed domain logic like how many violations constitutes a review in our database querying logic. Like all the examples I can find for this operation do.
It seems at best that our option is to use some sort of bulk api for this, which seems unnecessary for such a simple operation. Making the bulk api perform a thousand separate replaces seems ineffective to me, but I might be wrong here?
In other storage technologies and more mature API's all the code necessary to perform this operation is (example Entity framework);
db.UpdateRange(stocks);
await db.SaveChangesAsync();
Is this tracked as a feature request for the Mongo project somewhere?
In MongoDB, you are allowed to replace an existing document with a new document in the collection with the help of db. collection. replaceOne() method. This method will replace the existing document with the replacement document.
Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.
To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.
Bulk API can handle it see code below:
var updates = new List<WriteModel<CosmosDoc>>();
foreach (var doc in docs)
{
updates.Add(new ReplaceOneModel<CosmosDoc>(doc.Id, doc));
}
await MongoDb.DocsCollection.BulkWriteAsync(updates, new BulkWriteOptions() { IsOrdered = false });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With