56

In MongoDB how do you use $set to update a nested value?

For example, consider a collection people with the following document:

{
  _id: ObjectId("5a7e395e20a31e44e0e7e284"),
  name: "foo",
  address: { street: "123", town: "bar" }
}

How do I update the street field embedded in the address document from "123" to "Main Street"?

chridam
  • 100,957
  • 23
  • 236
  • 235
Drew LeSueur
  • 19,185
  • 29
  • 89
  • 106

2 Answers2

106

Using the dot notation:

db.people.update({ }, { $set: { "address.street": "Main Street" } })
Niels van der Rest
  • 31,664
  • 16
  • 80
  • 86
  • 10
    Does this work even if address does not exist? I know $set will create street if it doesn't exist on address but what is the behavior if the ancestral properties don't exist? Also, your link requires a login. – tleef May 15 '14 at 03:25
  • 3
    @Tom, thanks for the heads-up about the link, I've fixed it. To answer your question: it will create the required ancestral properties for you if they don't exist. – Niels van der Rest May 15 '14 at 18:23
  • 6
    @Tom Yes it will. It will create the whole object down to the field you're setting. (Late reply, but hopefully this is useful to others stumbling on this question) – Nepoxx Mar 21 '17 at 20:39
  • How to set the same field if it address is an array. For Example : { _id: ObjectId("5a7e395e20a31e44e0e7e284"), name: "foo", address: [{ street: "123", town: "bar" }] } – prit kalra Sep 27 '18 at 12:45
  • How can I use the existing values of an embedded array? Also see https://stackoverflow.com/questions/69494035/how-to-use-set-and-dot-notation-to-update-embedded-arraa-while-using-matching-a – Stefan Oct 08 '21 at 10:04
  • is there another way to do this? in my case there is an update request with properties, and if possible i would like to skip converting all fields to dot notation which would require each field to be mentioned in my code again. – Jeremias Nater Jul 14 '22 at 08:53
  • 1
    This DOES NOT WORK if the root node (`address`) is already set to `null` expilicitly. Updates would fail silently! – philoj Sep 12 '22 at 13:08
2

In addition to Niels' answer, also do verify the "type" of the nested value. In my case, it was a "string" formed from json. Though this might be unlikely, but do ensure that the value has the right type.

user2725012
  • 61
  • 1
  • 5