首页 > 解决方案 > MongoDB 如何在嵌套结构中查找和更新数据

问题描述

我的 mongoDB (v3.6.4) 有问题,下面是我的数据现在的样子。我需要在“second_list”中找到(并更新)某个元素的“text”值,即返回“hello”并在下一步将其更改为“hello world”。

{
  "_id": ObjectId("xxxxxxxxxxxxx"),
  "top_list": [
    {
      "create_time": "2019-06-10 15:56:46",
      "second_list": [
        {
          "name": "v1",
          "text": "hello"
        },
        {
          "name": "v2",
          "text": "good morning"
        },
        {
          "name": "v3",
          "text": "bye"
        }
      ]
    }
  ]
}

我试过这个查询

    db.myCollection.find(
            {'top_list.second_list.name':'v1'},
            {"top_list.second_list":1,"_id":0}
        )

但它返回了整个“second_list”。我想要的应该是

{
          "name": "v1",
          "text": "hello"
}

或者只是字符串“hello”。

标签: mongodb

解决方案


此语法适用于我查找和更新值

db['myCollection'].findAndModify({query:{_id: ObjectId("xxxxxxxxxxxxx")}, update: {$set: {"top_list.second_list.0.text":"someNewText"}}})

0 intop_list.second_list.0.text是您要访问的数组索引


推荐阅读