【问题标题】:How to delete a field in all documents of mongodb collection using MongoRepositoty @Query如何使用 MongoRepository @Query 删除 mongodb 集合的所有文档中的字段
【发布时间】:2022-06-23 04:29:34
【问题描述】:

我有一个收藏:

public class Person {
  private String name;
  private Integer age;
}

我想删除所有文档中的字段age。所以架构看起来像这样:

public class Person {
  private String name;
}

我正在使用 MongoRepositoty,我一直在尝试编写这个方法:

@Repository
public interface PersonRepository extends MongoRepository<Person, String> {
    @Query("{$updateMany: [ {}, { $unset: {'age': ''} }]}")
    void deleteAgeField();
}

我尝试了不同的括号和引号,但都以错误告终。我的语法有什么问题?我发现它与我们在 mongo 控制台中编写查询的方式不同。例如,此处不允许使用圆括号和双引号。

【问题讨论】:

    标签: mongodb mongodb-query spring-mongodb spring-repositories


    【解决方案1】:

    你可以简单地使用

    @Query(value = "{}", delete = true)
    void deleteAgeField();
    

    【讨论】:

    • 我猜它会删除所有person 文档,而不仅仅是age 字段。我说的对吗?
    • 是的,我的错。我会改正的。
    【解决方案2】:

    我发现的一个解决方案就是将该字段设置为空:

    repository.findAll().forEach(
            person -> {
                person.setAge(null);
                repository.save(person);
            });
    

    由于 Mongo 不是关系数据库,它包含文档而不是表。它具有对象的 json 表示,当字段 = null 时,它会消失。可能我的解释有点曲解,如有错误请指正。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 2018-08-08
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2017-02-21
      相关资源
      最近更新 更多