Search code examples
javascriptmongodbmeteor

Updating only certain sub documents in MongoDB


Given a document as such

{
  _id: '123456',
  items: [{
     itemId: 'abcd',
     qty: 1
  }, {
     itemId: 'defg',
     qty: 3 
  }]
}

I want to only update certain items; for example, I only want to increment itemId = 'abcd' 's quantity by 5, such that the resulting doc would become

{
  _id: '123456',
  items: [{
     itemId: 'abcd',
     qty: 6
  }, {
     itemId: 'defg',
     qty: 3 
  }]
}

How do I do that?


Solution

  • Basically there are 3 steps :

    1. Select the itemid from items array where value is abcd
    2. Use $inc property to increment
    3. Use $ operator (positional update) to specify that you want to

    Increment the qty key from the document to be updated.

    PFB final query :

    db.schools.update({ 
        items.itemId: 'abcd'
    },{
        $inc : { items.$.qty : 5 }
    });