Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simply perform a update/replace many documents operation in MongoDb

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?

like image 720
Kdog Avatar asked Jul 27 '18 13:07

Kdog


People also ask

How do I replace a document in MongoDB?

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.

How do I update multiple columns in MongoDB?

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.

How do you update an array of objects in MongoDB?

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.


1 Answers

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 });
like image 90
user3716465 Avatar answered Sep 21 '22 09:09

user3716465