Batch update with Mongoose

我的未来我决定 提交于 2021-02-06 11:21:32

问题


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?


回答1:


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




回答2:


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/



来源:https://stackoverflow.com/questions/12161538/batch-update-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!