Search code examples
node.jsmongodbmongooseincrement

MongoDB Increment Array of objects


Can someone help me how to properly make a update increment query for my data

For example I would like to increment the quantity of Unix Mug by 1, by the user with email: "[email protected]"

This one doesn't work for me

UserData.updateOne({email: email}, { $inc : {items: [{quantity: 1}]}})

enter image description here


Solution

  • You can use the positional operator ($) as shown below:

    db.users.updateOne({
      email: "USER_EMAIL",
      "items.productName": "Unix Mug"
    }, {
      $inc: {
        "items.$.quantity": 1
      }
    })