6

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.

4
  • 1
    Why did you ask the question if you already knew the answer? Also possible duplicate stackoverflow.com/questions/16037788/… Commented Dec 9, 2015 at 12:45
  • 2
    @SarathNair it is completely okay. albeit it is a duplicate. meta.stackoverflow.com/questions/290038/… Commented Dec 9, 2015 at 12:46
  • @Idos "So I came up with a question, did my research, and found no help on S.O" the question has already been anwered here in SO Commented Dec 9, 2015 at 12:47
  • I have seen the question mentioned and I think there is enough difference to add as separate. In my case it is referenced by index, not by matching value. Commented Dec 9, 2015 at 13:08

1 Answer 1

6

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}}) 
Sign up to request clarification or add additional context in comments.

1 Comment

What if the array does not actually exist? Instead of creating [1], it creates {"0": 1}. How can I ask it to use integer keys there?

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.