I am currently trying to figure out how to update documents in MongoDb via Spring Data. Of course, there is mongoTemplate.updateFirst and so on. But consider this:
User u = mongoTemplate.findOne(new Query(Criteria.where("_id").is(s)), User.class);
if (u == null) throw new UsernameNotFoundException("user " + s + " does not exist");
Session.setCurrentUser(u);
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(s)), new Update().inc("logincount", 1), User.class);
… query a user, on null throw a exception, if found increment logincount by 1. Works perfectly. But is this the right way? Do I have to query for the user again? Can’t I modify the object and re-save it?
You should probably use the upsert semantics.
See the answer in this post: MongoDB and upsert issue