Home > Net >  mongodb - How to update a value inside an array?
mongodb - How to update a value inside an array?

Time:11-02

I am trying to update the following row:

{
    "_id": "80a7",
    "title": "Is React better than Angular?",
    "options": [{
        "option": "Yes",
        "vote": 0
    }, {
        "option": "No",
        "vote": 0
    }],

Assuming in api/vote, the value passed is "Yes", How can I update the vote for Yes by $inc by 1 ?

  const {id, option} = req.body;

  const db = await getMongoDb();

  await db.collection('polls').updateOne(
    {
    _id: id,
    },
    {
      $set: {
        options: ???,
      },
    },
  );

What should be ??? replaced with?

CodePudding user response:

Work with arrayFilters.

await db.collection('polls').updateOne({
  _id: id
},
{
  $inc: {
    "options.$[opt].vote": 1
  }
},
{
  arrayFilters: [
    {
      "opt.option": "Yes"
    }
  ]
})

Demo @ Mongo Playground

  • Related