Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an element in all documents in a MongoDB collection

I am running the following query with the purpose of updating a single element in all the existing documents in the collection. I am basically trying to clear their value to "0".

Here is the code:

MongoCollection collection = db.GetCollection(DataAccessConfiguration.Settings.CollectionName);
var query = Query.Exists("ElementName", true);
var update = Update.Set("ElementName", "0");
collection.Update(query, update);

It only updates a single document.

How can I update all elements at once?

like image 278
agarcian Avatar asked Dec 25 '11 22:12

agarcian


People also ask

Which command is used to update all documents in a collection?

MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

How do I update an element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.


1 Answers

Updates in MongoDB affect 0 or 1 documents by default (0 only if the query specifier doesn't match anything). To update all documents, you need to pass UpdateFlags.Multi as the third argument Update. There is also a 4-argument version of Update which accepts the "safe mode" flag as the fourth argument.

(Safe mode bundles a getLastError command with the update, and causes the driver to wait until the server acknowledges that the write has succeeded. There are various options to safe mode that will wait for acknowledgement from multiple servers if you are using a replica set, that will wait only for a certain period of time and then return with an error, etc).

Also be sure to see the C# driver documentation for details on the API.

like image 108
dcrosta Avatar answered Sep 19 '22 02:09

dcrosta