How to update an *entire* nested document?

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 the make field of the embedded details document. The code format looks similar to the following code example, which instead replaces the entire embedded document, removing all other fields in the embedded details 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?

You can’t because you are not doing exactly the same thing as the example.

You are not using the same syntax. It is subtle but it is very important.

In

you are using the normal update operation while in

you use update with aggregation. Different syntax (the square brackets) different behaviour.

Normal

With aggregation

2 Likes

oh my god, i can’t believe i missed that.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.