MongoDB обновляет поле документа в массиве массивов

#node.js #arrays #mongodb #mongodb-query #aggregation-framework

Вопрос:

Как обновить ($set) поле «текст», соответствующее «callback_data»:»нравится» в документе, подобном этому:

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

Ответ №1:

Демо — https://mongoplayground.net/p/_g9YmDY5WMn

Использование — обновление-документов-с-агрегацией-конвейер

$карта $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
})