MongoDB - 更新嵌套数组中的对象 [英] MongoDB - Update an object in nested Array

查看:47
本文介绍了MongoDB - 更新嵌套数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
  "_id": "xPBc4By8FemDwTPqH",
  "u": {
    "_id": "6PoZawHZcQz4Gwzcv",
    "username": "michael"
  },
  "friends": [
    {
      "u": {
        "_id": "eGqDjAjjtYADbuSnn",
        "username": "michael",
        "name": "michael"
      }
    },
    {
      "u": {
        "_id": "k4gKCGwYryXDMMHvs",
        "username": "joyce",
        "name": "joyce"
      }
    }
  ]
}

我想更新friends.u.username"的名字:michael"的名字是hello",我需要怎么做.

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

推荐答案

应用 $set 运算符与 $ 位置运算符 在您的更新中更改 name 字段.

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

这篇关于MongoDB - 更新嵌套数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆