according to the update
documentation, using $set
with a nested document should replace the entire nested document:
The above code uses
dot notation
to update themake
field of the embeddeddetails
document. The code format looks similar to the following code example, which instead replaces the entire embedded document, removing all other fields in the embeddeddetails
document:
db.products.updateOne(
{ _id: 100 },
{ $set: { details:
{make: "Kustom Kidz"}
}
})
but i can’t seem to reproduce this behavior, when i try a simple example, it still leaves the old fields in the nested document.
[
{
"_id": ObjectId("63a00087347cec20308de2ec"),
"food": {
"expires": ISODate("2016-05-18T16:00:00Z"),
"type": "Banana"
}
}
]
db.collection.update({},
[
{
$set: {
"food": {
"type": "Watermelon"
}
}
}
],
{
upsert: true
})
[
{
"_id": ObjectId("63a00087347cec20308de2ec"),
"food": {
"expires": ISODate("2016-05-18T16:00:00Z"),
"type": "Watermelon"
}
}
]
what is going on here?