runtimeZero
runtimeZero

Reputation: 28116

update objects within a array inside a mongo document

For a mongo collection that looks like below:

{
  {
    site: 'one',
    twoWheelers: [
         { engine: 'honda',  qty:5 }
         { engine: 'yamaha', qty:6 }     
        ],
    fourWheelers: [ ..],
    eightWheelers: [ .. ]
  },
  { 
    site : 'two',
    twoWheelers: [
         { engine: 'honda',  qty:13 }
         { engine: 'yamaha', qty:16 }     
        ],
    fourWheelers: [ ..],
    eightWheelers: [ .. ]
  },
  {
    site: 'three',
    twoWheelers: [
         { engine: 'honda',  qty:2 }
         { engine: 'yamaha', qty:10 }     
        ],
    fourWheelers: [ ..],
    eightWheelers: [ .. ]
  },
}

I am writing a query to find all twoWheelers that have a 'honda' engine and update it's quantity by one

my update query looks something like below:

db.stock.update(
{ 'twoWheelers.engine' : 'honda'},
{ /*update statement here */ },
{ multi: true}
)

What confuses me is how do i target that exact index within the twoWheeler array for the update ?

please note: my search works fine and returns the documents that should be updated.

Upvotes: 0

Views: 74

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

The $ positional update operator represents the index of the first matched array element in each document, so you can use that in the update call like this:

db.stock.update(
  { 'twoWheelers.engine': 'honda'},
  { $inc: { 'twoWheelers.$.qty': 1 } },
  { multi: true}
)

Upvotes: 1

Related Questions