How to perform partial update with Spring data mongoDB(MongoOperations)
If you want to set an arbitrary number of fields (but not overwrite others), you can add a function to your model that turns it into a Map
. If you're in Spring
obviously Jackson
is a good choice for this.
From there you can remove all null
values and then add each field that does have a value to a $set
operation.
Map<String, Object> objectMap = user.toMap();
objectMap.values().removeIf(Objects::isNull);
Update update = new Update();
objectMap.forEach(update::set);
return mongoOperations.findAndModify(
Query.query(Criteria.where("_id").is(user.getId())), update, User.class);
Yes you can call selective updates
Query query = new Query(new Criteria("id").is(user.getId()));
Update update = new Update().set("name", user.getName()).set("email", user.getEmail());
mongoOperations.updateFirst(query, update, COLLECTION);