Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch update with Mongoose

I'm pulling data from a RETS(XML) feed and saving it in a local MongoDB using node and mongoose.

Periodically I need to update the documents and delete the inactive ones as well as add new ones. Rather than making multiple queries to Mongo or the RETS server, I was pulling both and looping through the data.

This works fine but is there a way to save the Mongoose results back to the database with updates and inserts? Or do I need to find each document and update it individually?

like image 913
jabbermonkey Avatar asked Aug 28 '12 14:08

jabbermonkey


Video Answer


2 Answers

On MongoDB, to update multiple documents (not just one) using Mongoose you can use the multi option:

Model.updateMany({ 
  size: 'lage'
}, { 
  $set: { size: 'large' }
});

See more on in the Mongoose documentation for updating documents and here

like image 62
Gianfranco P. Avatar answered Nov 11 '22 12:11

Gianfranco P.


For completeness, If any one has multiple query conditions and want to add new fields for every matching documents of query condition then we can go with

var bulk = Person.collection.initializeUnorderedBulkOp();
bulk.find(query1).update(update1);
bulk.find(query2).update(update2);
bulk.execute(callback);

In following documentation, it is said that db.collection.initializeUnorderedBulkOp()

Initializes and returns a new Bulk() operations builder for a collection. The builder constructs an unordered list of write operations that MongoDB executes in bulk. MongoDB executes in parallel the write operations in the list.

https://docs.mongodb.org/v3.0/reference/method/db.collection.initializeUnorderedBulkOp/

like image 45
Sandeep Sharma Avatar answered Nov 11 '22 10:11

Sandeep Sharma