1

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?

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • the update command on the mongo shell should work : db.cols.update({"items.itemId":"abcd"},{$set:{"items.$.qty":5}}). you need to use the $ operator to update an element in an array. – Hakan Özler May 03 '17 at 14:47
  • Possible duplicate of [Updating embedded document property in Mongodb](http://stackoverflow.com/questions/6758339/updating-embedded-document-property-in-mongodb) – Alex Blex May 03 '17 at 14:53

1 Answers1

2

Basically there are 3 steps :

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

increament the qty key from the document to be updated.

PFB final query :

db.schools.update({ 
    items.itemId: 'abcd'
},{
    $inc : { items.$.qty : 5 }
});
Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37
  • I thought the `$` operator would update *every* sub documents, but you are telling me that the database is smart enough to match an update only the matched subdocuments? – Yanick Rochon May 03 '17 at 15:14
  • Yes so first argument to the update is the query using which we will filter out the documents first and then second argument is something which will tell what to update in those filtered documents.. – Mihir Bhende May 03 '17 at 15:20
  • 1
    Field update operators like $inc and $set do not update every sub document, they only modify specified field. – adi May 03 '17 at 15:21
  • Yes adi, it will modify the particular field only.. not the entire document. – Mihir Bhende May 03 '17 at 15:23