Update all elements in an array in mongodb

I have a mongodb file, for example:

{ "name" : "JohnDoe", "adds" : [ { "status" : "PENDING", "date" : "2015-09-23" }, { "status" : "PENDING", "date" : "2015-10-01" } ] } 

I want to update the entire array of elements, for example:

 collection.update({'name':'JohnDoe'}, {'$set':{'adds.status':'APPROVED'}}). 

How to do it?

EDIT: Most solutions say to use a positioning operator to select an array element, and then use the operator to update that element. But in my case, I have to update every element in the array.

-1
source share
1 answer

As already mentioned, the main problem here is updating several elements with the positional operator recorded in this long-term problem: http://jira.mongodb.org/browse/SERVER-1243

Thus, the main case is that one execution cannot do this, so to process several elements of the array, you need some method of determining the number of elements needed to update and process one update statement for each element.

A simplified approach to this usually uses "Bulk Operations" to handle what ultimately is a "multitasking" update process in the form of a single request and response to the server:

 var bulk = db.collection.initializeOrderedBulkOp(), count = 0; db.collection.find({ "name": "John Doe", "adds.status": "PENDING" }).forEach(function(doc) { doc.adds.filter(function(add){ return add.status = "PENDING" }).forEach(function(add) { bulk.find({ "_id": doc._id, "adds.status": "PENDING" }).updateOne({ "$set": { "adds.$.status": "APPROVED" } }); count++; // Execute once in 1000 statements created and re-init if ( count % 1000 == 0 ) { bulk.execute(); bulk = db.collection.initializeOrderedBulkOp(); } }); }); // Execute any pending operations if ( count % 1000 != 0 ) bulk.execute(); 

If your updated documents are quite small or really only one document, you can refuse to check the count and simply add all the bulk updates to the desired cycles and simply execute once at the end of all cycles.

A more detailed explanation and alternatives can be found in How to update multiple elements of an array , but they all come down to different approaches to matching an element for updating and processing positional $ update mutliple times, for each agreed document or until more changed documents are returned .

+1
source

All Articles