'Update unique nested array element in Mongodb
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.
Solution 1:[1]
You need to use positional operator
db.collection.update({
"instock.warehouse": "C",
"item": "journal"
},
{
$set: {
"instock.$.qty": 10
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gibbs |
