57
{
  "_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.

ButterDog
  • 5,115
  • 6
  • 43
  • 61
徐巧民
  • 573
  • 1
  • 4
  • 5

4 Answers4

107

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" } }
)

To update multiple elements in an array when more than one element matches the filter, you can use the $\[<identifier>\] syntax with the arrayFilters option. The following will update all matching elements in the "friends" array:

db.collection.update(
    { "friends.u.username": "michael" },
    { "$set": { "friends.$[elem].u.name": "hello" } },
    { 
      "arrayFilters": [{ "elem.u.username": "michael" }], 
      "multi": true 
    }
)

The $[elem] syntax identifies array elements that match the specified filter in the arrayFilters option. The multi: true option is added to update all matching documents instead of just the first one.

chridam
  • 100,957
  • 23
  • 236
  • 235
  • 1
    For some reason is not working for me... Nothing happen, but If I use `0` instead of `$`, the (wrong) element on array is changed – Dherik Mar 07 '18 at 17:07
  • @Dherik Do you have a question already with the details for your problem? If not can you create one with a sample document and your desired result? – chridam Mar 07 '18 at 17:32
  • I will try a bit more. Maybe is some driver problem with Robo3T and backward compatibility: https://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb/46054172#46054172. If nothing works, I will open a question. Thank you! :) – Dherik Mar 07 '18 at 17:44
  • 2
    I'm using MongoDB 3.2.0. Apparently this version not supports this kind of operation. – Dherik Mar 07 '18 at 18:14
  • 2
    For me this only modified a single element. If more than one element matched, only the first will be updated – Mr.Cat Nov 07 '22 at 15:36
  • 1
    indeed this only updates first matching nested element. don't know how to allow for multiple matches (updates) – yBother Apr 05 '23 at 09:38
8

You can use $set operator.

> db.test.update({"friends.u._id":"eGqDjAjjtYADbuSnn"},{$set:{"friends.$.u.name":"hello"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
styvane
  • 59,869
  • 19
  • 150
  • 156
Srivatsa N
  • 2,291
  • 4
  • 21
  • 36
0

Below should work fine as its tested

First check the current value of the array.

db.test.findOne({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{"friends.u.name":1})

Now fire the update command

db.test.update({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{$set:{"friends.$.u.name":"hello"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now check the results again to validate the update values

db.test.findOne({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{"friends.u.name":1})

Hope this helps.

Sanjay Bharwani
  • 3,317
  • 34
  • 31
0

If you are using python, I created this function to generate the new update:

def generate_set_to_update_document(field: str, changes: dict) -> dict:
    new_set = {}
    for change in changes.keys():
        new_set[f"{field}.$.{change}"] = changes[change]
    return new_set
Marcos Viana
  • 91
  • 1
  • 4