Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between updateMany() and bulkWrite() in mongoose?

AFAIK, both operations can update multiple documents. If so, what is the difference between the two?

like image 362
omer Avatar asked Jun 03 '19 17:06

omer


People also ask

What is bulkWrite in MongoDB?

In MongoDB the db. collection. bulkWrite() method performs multiple write operations with controls for order of execution. Bulk write operations affect a single collection.

What is the difference between update and updateOne in MongoDB?

can someone clarify what is the difference between them. updateMany: updates all the documents that match the filter. updateOne: updates only one documnet that match the filter.

Why are ordered transactions slower than unordered transactions in MongoDB?

Executing an ordered list of operations on a sharded collection will generally be slower than executing an unordered list since with an ordered list, each operation must wait for the previous operation to finish.

What is the principal implication of using a bulk write operation in MongoDB?

bulkWrite() method provides the ability to perform bulk insert, update, and delete operations. MongoDB also supports bulk insert through the db. collection.


1 Answers

Just quoting the API docs here

bulkWrite

Sends multiple insertOne, updateOne, updateMany, replaceOne, deleteOne, and/or deleteMany operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) if you use create()) because with bulkWrite() there is only one round trip to MongoDB.

Mongoose will perform casting on all operations you provide.

This function does not trigger any middleware, not save() nor update(). If you need to trigger save() middleware for every document use create() instead.

updateMany

Same as update(), except MongoDB will update all documents that match filter (as opposed to just the first one) regardless of the value of the multi option.

Note updateMany will not fire update middleware. Use pre('updateMany') and post('updateMany') instead.

(emphasis mine)

To see examples of use take a look at the ones provided in the function's respective documentation.

like image 166
Misantorp Avatar answered Sep 19 '22 11:09

Misantorp