1

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"
        }]
    ]
}

1 Answer 1

1

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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.