Spring Mongodb Data: Document Updates

I'm currently trying to figure out how to update documents in MongoDb through Spring Data. Of course there is mongoTemplate.updateFirst and so on. But consider the following:

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

... to request the user, with a zero exception throw, if increment logincount is found to be 1. It works fine. But is that right? Do I need to request the user again? Can I change the object and re-save it?

+2
source share
3 answers

You should probably use upsert semantics.

See the answer in this post: MongoDB and upgrade issue

+1
source

, - :

WriteResult result = mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(s)), new Update().inc("logincount", 1), User.class);
if (result.getN() != 1) {
   throw new UsernameNotFoundException("user " + s + " does not exist");
}
+3

If you are using an entity inside and outside the template usage view, do the following:

User user = template.findOne(query(where("id").is(id)), User.class);
// manipulate object
template.save(user);

You may also want to take a look at the repositories as they do not require you to formulate the queries yourself.

+1
source

Source: https://habr.com/ru/post/1607869/


All Articles