omer
omer

Reputation: 1442

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?

Upvotes: 15

Views: 13150

Answers (1)

Misantorp
Misantorp

Reputation: 2821

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.

Upvotes: 21

Related Questions