AFAIK, both operations can update multiple documents. If so, what is the difference between the two?
In MongoDB the db. collection. bulkWrite() method performs multiple write operations with controls for order of execution. Bulk write operations affect a single collection.
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.
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.
bulkWrite() method provides the ability to perform bulk insert, update, and delete operations. MongoDB also supports bulk insert through the db. collection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With