MongoDB - Update an object in nested Array

徐巧民 picture 徐巧民 · Dec 23, 2015 · Viewed 46.3k times · Source
{
  "_id": "xPBc4By8FemDwTPqH",
  "u": {
    "_id": "6PoZawHZcQz4Gwzcv",
    "username": "michael"
  },
  "friends": [
    {
      "u": {
        "_id": "eGqDjAjjtYADbuSnn",
        "username": "michael",
        "name": "michael"
      }
    },
    {
      "u": {
        "_id": "k4gKCGwYryXDMMHvs",
        "username": "joyce",
        "name": "joyce"
      }
    }
  ]
}

I want to update the name of "friends.u.username": "michael" 's name is "hello", how I need to do it.

Answer

chridam picture chridam · Dec 23, 2015

Apply the $set operator together with the $ positional operator in your update to change the name field.

The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:

db.collection.update(
    { "friends.u.username": "michael" }, 
    { "$set": { "friends.$.u.name": "hello" } }
)