MongoDB - Update an object in nested Array

主宰稳场 提交于 2019-11-26 06:02:38

问题


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


回答1:


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



回答2:


You can use $set operator.

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



回答3:


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.



来源:https://stackoverflow.com/questions/34431435/mongodb-update-an-object-in-nested-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!