【问题标题】:Updating a nested array object in Mongo db在 Mongodb 中更新嵌套数组对象
【发布时间】:2019-03-11 03:44:55
【问题描述】:

这是json对象

{
"account_id":"1",
"sections":[ {
    "section_name":"abc",
    "labels": [{
        "name": "label1",
        "value": "value1"
        },
        {
        "name": "label2",
        "value": "value2"
        }]
    },
     {
    "section_name":"def",
    "labels": [{
        "name": "label3",
        "value": "value3"
        }]
    }]
}

在这个 json 对象中,我想在 def 部分将 label3 的值从 value3 更改为 value4。有不同的帐户,但我在这里只列出了一个 json 对象。

我使用了下面的代码,但它对我不起作用。这里我传递了节名(section)、标签名(label)和标签值(value)。

let query = {
account_id: event.accountId.toString(),
sections: {
    section_name: section,
    labels: {
    label_name: label
       }
     }
   };

   return using(connectDatabase(), db => {
   return db.collection(TABLE_NAME).updateOne(query, { $set: { 
  'sections.$.labels.$.value': value } });
  }).then(
    result => {
      cb(null, responseObj(result, 200));
    },
    err => {
      cb(responseObj(err, 500));
    }
  );

有人可以帮助我吗?提前致谢

【问题讨论】:

  • 运行该查询时是否有任何错误?
  • 它没有在数据库中更新。
  • 使用arrayFilters发布答案,希望它对你有用

标签: node.js mongodb


【解决方案1】:

为了达到预期的效果,请使用下面的使用 arrayFilters 嵌套对象的选项

  • 使用 account_id 获取主对象
  • 使用 ArrayFiter $[identfier].section : "def"$[identfier].name: "label3"

 db.collection(TABLE_NAME).updateOne({
    account_id: event.accountId.toString(),
    {
      "$set": {
        "sections.$[elem].labels.$[label].value": value
      }
    },
    {
      "arrayFilters": [{
        "elem.section_name": section
      }, {
      "label.name": label
      }]
    }
})

请参阅此链接了解更多详情 - https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

arrayFilters 的另一个例子 - How to Update Multiple Array Elements in mongodb

【讨论】:

  • "不支持的投影选项:$set: { section.$[elem].labels.$[label].value: \"valllll\" }",
  • 我已经在 RoboMongo 中检查过了。这会影响这个错误吗?
  • @UthpalaPitawela,应该用引号括起来 -sections.$[elem].labels.$[label].value
  • 我认为problelm是mongo版本,它只适用于3.6以上的版本,而我的mongo版本低于3.6
  • oh k @UthpalaPitawela :) ,您是尝试升级到 3.6 还是尝试为低于 3.6 的版本寻求解决方案?
【解决方案2】:

更新的查询 您可以使用此查询

db.testcol.update(
   { },
   { $set: { "sections.$[element].labels.$[element1].value" : "value1New" } },
   { multi: true,
     arrayFilters: [ { "element.section_name": { $eq: "abc" } },  { "element1.name": { $eq: "label1" } }]
   }
)

您可以检查以下查询:其中 1 是数组的索引值。

db.testcol.update(
    {
        account_id:"1", 
        "sections.section_name":"def"
    }, 
    {
        $set:{
            "sections.1.labels.1.value":"value8"
        }
    }
) 

如果要更新所有值,则可以使用:

db.testcol.update(
{
    account_id:"1", 
    "sections.section_name":"def"
}, 
{
    $set:{
        "sections.$[].labels.$[].value":"value8"
    }
}

)

请检查并告诉我是否有帮助。

【讨论】:

  • 这不适用于 section.1.labels.1.value":"value8 ,更新索引 1,有时预期的标签并不总是在索引 0 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
相关资源
最近更新 更多