如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:03:43  来源:igfitidea点击:

How do I update Object with Spring Data and MongoDB?

springmongodbspring-dataspring-data-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

If you read the javadocfor MongoOperations/MongoTemplate you will see that

如果您阅读MongoOperations/MongoTemplate的javadoc,您将看到

save()

performs an:

执行:

upsert() 

So yes you can just update your object and call save.

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

回答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);