0

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.

1 Answer 1

1

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}
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.