Search code examples
mongodbspring-data-mongodbmongodb-java

update mongodb document using java object


I have one User class like this:

@Document(collection = "users")
public class User {

    @Id
    private String id;

    String username;

    String password;

    String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "User[id=" + id + ", username=" + username + ", password=" + password + ", description"
                + description + "]";
    }

}

I am able to perform limited update. Like:

Query searchQuery = new Query(Criteria.where("id").is("shashi"));
        mongoDBClient.updateFirst(searchQuery, Update.update("password", "newpassword"), User.class);

Now if I want to update rest other fields(username and description) of User class, I need to call updateFirst method so many times.

I want to avoid this and pass the entire object to updateFirst method. Something like:

mongoDBClient.updateFirst(searchQuery, Update.update(userObject), User.class);

Basically, I want to edit all/multiple fields in one call using java POJO object. How I can achieve this?


Solution

  • Edit/All multiple fields in one call using java POJO object, can be done as shown below

    1) Query the document which need to be updated --> we get the java object

    2) Do all modifications in the java object

    3) Save the object

    Code:

    Query query = new Query();
    query.addCriteria(Criteria.where("id").is("shashi"));
    User user = mongoOperation.findOne(query, User.class);
    //modify the user object with the properties need to be updated
    //Modify password and other fields
    
    user.setPassword("newpassword");
    user.setDescription("new description");
    user.setUsername("NewUserName");
    //save the modified object
    mongoOperation.save(user);