1

I have a very simple example from official documentation page:

Data:

   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }

I want to update quantity where item = "journal" and warehouse = "A".

Item is always unique, warehouse is always unique within array elements.

For example I tried queries like this:

collection.updateOne(
"{ \"item\": \"" + item + "\", \"instock.warehouse\": \"" + warehouse + "\" } } }", // find
"{ $set: { quantity: \"" + quantity + "\" } }" // update
)

Issue is always the query, for example this query returns all elements... I tried about 100 different other ones but nothing is working.

I am using embedded db for tests right now from flapdoodle, version 3_4.

1
  • 1
    @Gibbs works, thanks a lot! I left a comment but seems it was deleted. Commented May 7, 2022 at 7:12

1 Answer 1

1

You need to use positional operator

Playground

db.collection.update({
"instock.warehouse": "C",
  "item": "journal"
},
{
  $set: {
    "instock.$.qty": 10
  }
})
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.