The data in mongodb is like this
{
"_id": "1",
"a": 1,
"b": 2,
"c": 3
"d": 4
}
I can update the document using a single "$set" operator.
db.collection.update({"_id": "1"}, {
"$set": {
"a": 100,
"b": 200,
"c": 300,
"d": 400
}
})
I can also update the document using multiple "$set" (each field has a "$set").
db.collection.update({"_id": "1"}, [
{
"$set": { "a": 100 }
},
{
"$set": { "b": 200 }
},
{
"$set": { "c": 300 }
},
{
"$set": { "d": 400 }
}
])
I would like to know if there are any performance concerns on the mongodb end by using the "multi-set" version. Is it Ok to use the "multi-set" version if, for some cases, I need to.
2
Answers
For your case, I think there will be a trivial performance difference, if not none. The
explain
plans for them are nearly identical.explain
output for single$set
:Mongo Playground
explain
output for multiple$set
:Mongo Playground
Given your query pattern in the example on updating on only 1 document and you are fetching by
_id
, I don’t think there will be any observable performance difference.There are 2 caveats outside of performance though:
$set
operations, you need to break them into different stagese.g. you
$set
a to be c * d = 12, and b to be a + 1 = 12 + 1 = 13. You will need to do:Mongo Playground
A single
$set
won’t give you expected result of b = 13, but 2 because a is yet to be evaluated as 12(keeping 1 as value)Mongo Playground
$set
statement more readable or manageable. But I will admit this is quite subjective and you may consider the other way round.Why do you think, someone "needs to do so"? The operators are JSON objects, you can create an update for example like this: