使用Spring data mongodb修改文档的某些属性

使用Spring data mongodb修改文档的某些属性,mongodb,spring-boot,jersey,spring-data-mongodb,Mongodb,Spring Boot,Jersey,Spring Data Mongodb,我想知道我正在尝试更新集合用户文档的一个或两个属性,该用户具有以下属性 { "id": "591fcd33f8bb03598ec34f70", "name": null, "username": "abc", "emailId": "abc@gmail.com", "interestedFlag": 1, "mobNo": "xxxxxxxxxx", "userActiveFlag": 1, "address": "1", "city": "abx", "

我想知道我正在尝试更新集合用户文档的一个或两个属性,该用户具有以下属性

{
  "id": "591fcd33f8bb03598ec34f70",
  "name": null,
  "username": "abc",
  "emailId": "abc@gmail.com",
  "interestedFlag": 1,
  "mobNo": "xxxxxxxxxx",
  "userActiveFlag": 1,
  "address": "1",
  "city": "abx",
  "state": "up",
  "profileImage": [
    {}
  ],
  "joinedOn": null,
  "modifiedOn": null,
  "lastVisited": null,
  "tempPassword": "1234567",
  "sex": null,
  "metaDataMap": {},
  "dob": null
}
假设我只想更新用户名,并且使用以下命令运行save:

userRepository.save(userEntity);
它将我的用户更改为:

{
  "id": "591fcd33f8bb03598ec34f70",
  "name": "New Name",
  "username": null,
  "emailId": null,
  "interestedFlag": null,
  "mobNo": null,
  "userActiveFlag": null,
  "address": null,
  "city": null,
  "state": null,
  "profileImage": null,
  "joinedOn": null,
  "modifiedOn": null,
  "lastVisited": null,
  "tempPassword": null,
  "sex": null,
  "metaDataMap": {},
  "dob": null
}
但理想情况下,我只想更改我的用户名

我的用户控制器是:

我的serviceImpl是:

我的假设是:


请帮助我用Spring data mongodb以正确的方式实现这一点。

正如大家在评论中所写的那样,您应该为此创建一个自定义更新方法

首先为自定义方法创建一个接口:

interface UserRepositoryCustom {
   void updateName(String userId, String newName);
}
然后将其添加到UserRepository:

此外,您应该始终只更新要更新的字段。
保存方法应该很少使用。

这会有所帮助。为此,您必须使用MongoTemplate
@Override
public User changeName(User user){
    User userEntity = userRepository.findById(user.getId());
    userEntity.setName(user.getName());
    return userRepository.save(userEntity);
}
public interface UserRepository extends MongoRepository<User, String>
interface UserRepositoryCustom {
   void updateName(String userId, String newName);
}
public interface UserRepository extends MongoRepository<User, String>, UserRepositoryCustom
public class UserRepositoryImpl implements UserRepositoryCustom {

    private final MongoTemplate mongoTemplate;

    public UserRepositoryImpl(@Autowired final MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void updateName(final String id, final String newName) {
        mongoTemplate
                .updateFirst(Query.query(Criteria.where(Entity.Meta.ID).is(id)),
                        Update.update("name", newName), User.class);
    }
}