MongoDB bulk operations have two options:
Adds a single document update operation to a bulk operations list. The operation can either replace an existing document or update specific fields in an existing document.
Adds a single document replacement operation to a bulk operations list. Use the
Bulk.find()
method to specify the condition that determines which document to replace. TheBulk.find.replaceOne()
method limits the replacement to a single document.
According to the documentation, both of these two methods can replace a matching document. Do I understand correctly, that updateOne()
is more general purpose method, which can either replace the document exactly like replaceOne()
does, or just update its specific fields?
With replaceOne()
you can only replace the entire document, while updateOne()
allows for updating fields.
Since replaceOne()
replaces the entire document - fields in the old document not contained in the new will be lost. With updateOne()
new fields can be added without losing the fields in the old document.
For example if you have the following document:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333
}
Using:
replaceOne({"_id" : ObjectId("0123456789abcdef01234567")}, { "my_test_key4" : 4})
results in:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key4" : 4.0
}
Using:
updateOne({"_id" : ObjectId("0123456789abcdef01234567")}, {$set: { "my_test_key4" : 4}})
results in:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333.0,
"my_test_key4" : 4.0
}
Note that with updateOne()
you can use the update operators on documents.