如何使用Spring Data和MongoDB更新Object?

use*_*795 5 spring mongodb spring-data spring-data-mongodb

如何使用Spring Data和MongoDB更新Object?

我只是做一个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;
    }
Run Code Online (Sandbox Code Playgroud)

Tre*_*ing 9

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

save()
Run Code Online (Sandbox Code Playgroud)

执行:

upsert() 
Run Code Online (Sandbox Code Playgroud)

所以是的,你可以只更新你的对象并调用save.

  • 请记住,save()将覆盖整个对象,而您可能只想更新文档的一部分。 (2认同)

小智 5

您可能可以在一行中同时执行“查找”和“更新”操作。

mongoTemplate.updateFirst(query,Update.update("Name", name),Person.class)
Run Code Online (Sandbox Code Playgroud)

您可以在Spring Data MongoDB Helloworld上找到一些出色的教程。


Akn*_*glu 5

您可以为此使用template.save()repository.save(entity)方法。但是 mongo 也Update反对这种操作。

例如:

Update update=new Update();
update.set("fieldName",value);
mongoTemplate.update**(query,update,entityClass);
Run Code Online (Sandbox Code Playgroud)