tomaskazemekas
tomaskazemekas

Reputation: 5168

How can I increment an array element referenced by index in 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.

Upvotes: 6

Views: 3484

Answers (1)

tomaskazemekas
tomaskazemekas

Reputation: 5168

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}}) 

Upvotes: 6

Related Questions