Let's say we have a collection with documents like this:
{
 _id : "some id",
 items: [
  {item: "item A", count: 5},
  {item: "item B", count: 3},
  {item: "item C", count: 9}
]
}
How can I increment the value by 1 of the third (or any other index value) element in items array?
And I want to reference not by matching value like in this question, but by index.
In the mongo shell it can be done this way:
db.my_collection.update(
 {_id: "some id"},
 {$inc: {"items.2.count": 1}}
)
Using PyMongo it can be done this way:
db.my_collection.update_one({"_id": "some id"},
                            {"$inc": {"items." + str(2) + ".count": 1}}) 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With