18

I´m using mongotemplate for Spring, and I was wondering how I could increment a value of one of my documents that I have in an array atomically. Imagine that we have

{'a':1,
   b:[{_id:341432,
       c:2
      },
      {_id:341445,
       c:3
      }]};

What I would like is increment c from 3 to 4 for the _id 341445

I have been using findAndModify but I dont know how can I make it for a nested document in an array.

Regards.

1
  • So far the only thing that I found is determinate the index of the array like b.0.c=11111 any better idea? Commented Apr 16, 2013 at 14:15

1 Answer 1

45

To update an element in an array field, you can use the positional $ operator

For example, the following js increments c from 3 to 4 for _id 341445:

db.collection.update({a:1, "b._id":341445} , {$inc:{"b.$.c":1}})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks!, but remember that your answer have to be extrapolated to Java
This will not work when the update query is used with upsert.
Thank You Thank You Thank You. I've been spending three+ hours trying to get this to work!!! Great answer!!
@Lind Qin, thanks it works. Here spring data solution for the ones who might be interested: mongoOperations.updateFirst(new Query(Criteria.where("a").is(1).and("b._id").is(341445)),new Update().inc("b.$.c", 1), YourClass.class);

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.