如何使用Spring Data和MongoDB更新对象?

9
我该如何使用Spring Data和MongoDB更新对象?
我只需要使用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;
    }
4个回答

13

如果您阅读了MongoOperations/MongoTemplate的Javadoc文档,您会发现:

save()

执行一个:

upsert() 

所以,是的,你可以直接更新你的对象并调用保存。


5
请注意,save() 方法将覆盖整个对象,而您可能只想更新文档的一部分。 - Robocide

7
您可以在一行代码中同时执行“查找”和“更新”操作。
mongoTemplate.updateFirst(query,Update.update("Name", name),Person.class)

你可以在Spring Data MongoDB Helloworld找到一些优秀的教程,涉及IT技术。


5
您可以使用template.save()repository.save(entity)方法来完成此操作。但是,Mongo还提供了用于此类操作的Update对象。
例如:
Update update=new Update();
update.set("fieldName",value);
mongoTemplate.update**(query,update,entityClass);

1
以下代码是使用MongoTemplate进行更新操作的等效实现。
public Person update(Person person){
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(person.getId()));
        Update update = new Update();
        update.set("name", person.getName());
        update.set("description", person.getDescription());
        return mongoTemplate.findAndModify(query, update, Person.class);
    }

2
我也看到过使用 Criteria.where("_id")。你能评论一下吗?例如,这两种变体都是功能性的吗?谢谢! - mapto
1
_id字段是每个文档的主键,也可以通过id访问。我们可以将id视为_id的别名。 - abhinav kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接