Mongodb在仅更新文档字段的一部分后不执行文档更新

时间:2017-03-27 11:45:18

标签: java spring mongodb

我正在使用spring boot version 1.4.2和mongodb 3.4.2

当我使用存储库接口在更改文档的某个属性后保留现有文档时,将保存旧文档。例如:

@Document(collection="UserDoc)
public class UserDoc{
@Id
private String id;    
private String userName;
private String passWord;
private int age;
//getters and setters...
}
@Autowired
private UserDocRepository userDocRepository;
UserDoc userDoc = userDocRepository.findOne("dummyId");
//assume the id passed in is correct and a UserDoc is returned.
//now when i change one of the fields,eg the age and save it back,the old 
//value gets persisted,eg if age is 10 and i change it to 5,the old property  
//is still persisted to db unless i Create a new UserDoc and copy all the 
//properties before it gets persisted with the correct value of 5.
userDoc.setAge(5);
userDocRepository.save(userDoc);//this is supposed to update the document 
//with a new value of 5 instead of 10 as it was probably per the assumption.

UserDoc userDocUpdated = new UserDoc();
userDocUpdated.setId(userDoc.getId);
userDocUpdated.setUserName(userDoc.getUserName);
userDocUpdated.setPassWord(userDoc.getPassWord);
userDocUpdated.setAge(5); //this way,the document is updated with 5 as the 
//age

userDocRepository.save(userDocUpdated);//this updates it accordingly with 
//the desired value of 5 for the age

第一个场景可能会出现什么问题?mongodb或spring boot会出现问题吗?任何见解都会很高兴。

1 个答案:

答案 0 :(得分:0)

遗憾的是我对java知之甚少,但

这就是你在做的事情:

private UserDocRepository userDocRepository;
UserDoc userDoc = userRepository.findOne("dummyId");
userDocRepository.save(userDoc);//this is supposed to update the document

这就是我认为你应该这样做的事情:

private UserDocRepository userDocRepository;
UserDoc userDoc = userDocRepository.findOne("dummyId");
userDocRepository.save(userDoc);//this is supposed to update the document
如果我错了,请纠正我:)