How to perform a partial upgrade using Spring data mongoDB (MongoOperations)

In my database I have a document similar to this

{
    "_id" : ObjectId("5864ddd8e38112fd70b89893"),
    "_class" : "com.apic.models.UserReg",
    "name" : "Bijay",
    "email" : "apic.apps@gmail.com",
    "psd" : "16d932a5a3da90cc6afd831016b5a6821f0badf7e2c624159205924433613c3a",
    "activationToken" : "fe8376ea2dbdf61ebc0f11a2361d741ba3178362d5bf876cf47e6a126bc5b39c",
    "verified" : false
}

I also have a bean that looks like

public class User {
  @Id
  private int id;
  private String name;
  private String email;

  // getter/setter methods

}

Therefore, when I try to call a method save() MongoOperations, it replaces all the missing properties, such as psd, verified, and activationToken.

mongoOperations.save(user, COLLECTION);

Is there a way where I can only update existing properties in a model class and leave them the same?

+4
source share
2 answers

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

( ), , Map. Spring, , Jackson - .

null, , , $set.

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

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


All Articles