Reputation: 3429
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?
Upvotes: 2
Views: 9209
Reputation: 3813
You could avoid the extra query by doing something like:
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");
}
Upvotes: 3
Reputation: 83051
If you're up for entity in and out kind of using the template just do the following:
User user = template.findOne(query(where("id").is(id)), User.class);
// manipulate object
template.save(user);
You also might wanna have a look at the repositories as they don't require you to formulate the queries actually.
Upvotes: 1
Reputation: 42342
You should probably use the upsert semantics.
See the answer in this post: MongoDB and upsert issue
Upvotes: 1