Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform partial update with Spring data mongoDB(MongoOperations)

In my database I have a document that looks like this

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

I also have a bean that looks like this

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

  // getter/setter methods

}

So when I try to call save() method of MongoOperations, it replaces all missing properties like psd, verified and activationToken.

mongoOperations.save(user, COLLECTION);

Is there any way where I can update only the existing properties in my models class and leave others as it is?

like image 828
BiJ Avatar asked Dec 29 '16 10:12

BiJ


2 Answers

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);
like image 164
Rossiar Avatar answered Oct 16 '22 11:10

Rossiar


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);
like image 22
Rahul Kumar Avatar answered Oct 16 '22 11:10

Rahul Kumar