简体   繁体   中英

MongoDB update a document field in Array of Arrays

How to update ($set) a field "text" that matching "callback_data":"like" in document like this:

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

Demo - https://mongoplayground.net/p/_g9YmDY5WMn

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM