I have created a ‘sequence’ collection. It has ‘name’ and ‘counter’ fields. The ‘name’ field is set to ‘Tag’ and ‘counter’ field is set to 0. Following is the code within a method that returns the next value of ‘counter’ field.
final Sequence tagSequence = mongoTemplate.findAndModify(
new Query(Criteria.where("name").is("Tag")),
new Update().inc("counter", 1),
new FindAndModifyOptions().returnNew(true), Sequence.class);
However, this piece of code does not work. Any inputs?
I found an implementation for this here, http://dev.bubblemix.net/blog/2011/04/auto-increment-for-mongodb-with-the-java-driver/, however, I wanted to know what is wrong with this piece of code.
Your code works correctly provided that you have first saved the Sequence object, with the “Tag” name, in MongoDB. I’d suggest you annotate the
namefield with the@Idannotation. Ex.:Save the object in MongoDB: