如何使用 Spring Data 和 MongoDB 更新对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17447426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I update Object with Spring Data and MongoDB?
提问by user2428795
How do I update Object with Spring Data and MongoDB?
如何使用 Spring Data 和 MongoDB 更新对象?
do I just do a template.save()?
我只是做一个template.save()吗?
public Person update( String id, String Name )
{
logger.debug("Retrieving an existing person");
// Find an entry where pid matches the id
Query query = new Query(where("pid").is(id));
// Execute the query and find one matching entry
Person person = mongoTemplate.findOne("mycollection", query, Person.class);
person.setName(name);
/**
* How do I update the database
*/
return person;
}
回答by Trevor Gowing
回答by Satheesh Kumar
You could probably do both 'find' and 'update' operations in one line.
您可能可以在一行中同时执行“查找”和“更新”操作。
mongoTemplate.updateFirst(query,Update.update("Name", name),Person.class)
You can find some excellent tutorials at Spring Data MongoDB Helloworld
您可以在Spring Data MongoDB Helloworld 中找到一些优秀的教程
回答by AknKplnoglu
You can just use template.save()or repository.save(entity)methods for this. But mongo has also Updateobject for this operations.
您可以为此使用template.save()或repository.save(entity)方法。但是 mongo 也Update反对这种操作。
For example:
例如:
Update update=new Update();
update.set("fieldName",value);
mongoTemplate.update**(query,update,entityClass);

