【问题标题】:MongoDB update a document field in Array of ArraysMongoDB 更新数组数组中的文档字段
【发布时间】:2021-07-20 05:51:13
【问题描述】:

如何在文档中更新($set)匹配“callback_data”:“like”的字段“text”,如下所示:

"data": {
    "buttons": [
        [{
            "text": "Button",
            "url": "https://example.org"
        }],
        [{
            "text": "????",
            "callback_data": "like"
        }, {
            "text": "????",
            "callback_data": "dislike"
        }]
    ]
}

【问题讨论】:

    标签: node.js arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    演示 - https://mongoplayground.net/p/_g9YmDY5WMn

    使用 - update-documents-with-aggregation-pipeline

    $map$mergeObjects$cond

    db.collection.update({},
    [
      {
        $set: {
          "data.buttons": {
            $map: {
              input: "$data.buttons",
              in: {
                $map: {
                  input: "$$this", // array inside buttons 
                  in: {
                    $cond: [
                      { $eq: [ "$$this.callback_data", "like" ] }, // condition
                      { $mergeObjects: [ "$$this", { text: "changed" } ] }, // true
                      "$$this" // false
                    ]
                  }
                }
              }
            }
          }
        }
      }
    ],
    {
      multi: true
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2016-12-31
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多