Suppose I have a doc structure like this:
thing: {
name: {
first: "John",
last: "Doe"
}
}
say I want to update the last name only. Which command do I send to update?
$set: {
name: {
first: "Connor"
}
}
or
$set: {
"name.first": "Connor"
}
Is there a difference? Or a preference? I much prefer the first since it resembles the actual document, but mongodb documentation uses the second method.
$setcommand will take the key and overwrite whatever was stored in it by the value you pass. So in this casethe whole subdocument
namewith potentially rich structure is getting replaced with a simple{first: 'Connor'}.Similar thing is happening in the second case, only it is one level deeper. In this case it’s a string, but it could be a hash as well.
You can update fields at arbitrary depth level by constructing proper dotted name. Here’s a slightly contrived example