【问题标题】:How do I update Object with Spring Data and MongoDB?如何使用 Spring Data 和 MongoDB 更新对象?
【发布时间】:2013-07-03 12:01:53
【问题描述】:

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

【问题讨论】:

    标签: spring mongodb spring-data spring-data-mongodb


    【解决方案1】:

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

    save()
    

    执行:

    upsert() 
    

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

    【讨论】:

    • 请记住 save() 将覆盖您的整个对象,而您可能有兴趣只更新文档的一部分。
    【解决方案2】:

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

    mongoTemplate.updateFirst(query,Update.update("Name", name),Person.class)
    

    您可以在以下位置找到一些优秀的教程 Spring Data MongoDB Helloworld

    【讨论】:

      【解决方案3】:

      您可以为此使用template.save()repository.save(entity) 方法。但 mongo 也有 Update 对象用于此操作。

      例如:

      Update update=new Update();
      update.set("fieldName",value);
      mongoTemplate.update**(query,update,entityClass);
      

      【讨论】:

        【解决方案4】:

        以下代码是使用 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);
            }
        

        【讨论】:

        • 我还看到Criteria.where("_id") 被使用过。你能评论一下吗?例如。两种变体都起作用吗?谢谢!
        • _id 字段是每个文档的主键,也可以通过 id 访问。我们可以将 id 视为 _id 的别名。
        猜你喜欢
        • 2015-02-22
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2012-05-18
        相关资源
        最近更新 更多