Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increment an array element referenced by index in MongoDB?

Tags:

mongodb

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.

like image 920
tomaskazemekas Avatar asked Dec 09 '15 12:12

tomaskazemekas


1 Answers

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}}) 
like image 180
tomaskazemekas Avatar answered Nov 15 '22 04:11

tomaskazemekas