如何使用MongorePositoty @Query删除MongoDB集合的所有文档中的字段

发布于 2025-02-04 09:10:54 字数 550 浏览 4 评论 0原文

我有一个集合:

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

我想在所有文档中删除字段。因此,模式看起来像这样:

public class Person {
  private String name;
}

我正在使用MongorePositoty,并且我一直在尝试编写此方法:

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

我尝试了不同的括号和引号,但这一切都遇到了错误。我的语法怎么了?我认为这与我们在Mongo控制台中编写查询的方式有所不同。例如,这里不允许圆括号和双引号。

I have a collection:

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

I want to delete field age in all the documents. So the schema gonna look like that:

public class Person {
  private String name;
}

I'm using MongoRepositoty and I've been trying to write this method:

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

I tried different brackets and quotes, but it all ends up with errors. What's wrong with my syntax? I see it differs from how we write queries in mongo console. For instance, round brackets and double quotes are not allowed here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

才能让你更想念 2025-02-11 09:10:54

您可以简单地使用

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

You could use simply

@Query(value = "{}", delete = true)
void deleteAgeField();
回忆那么伤 2025-02-11 09:10:54

我发现的一种解决方案只是将字段设置为null:

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

由于Mongo不是关系DB,因此它包含文档而不是表。它具有json的对象表示,当字段= null时,它消失了。也许我的解释有点扭曲,如果我错了,请纠正我。

A solution I've found is simply to set the field to null:

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

As Mongo is not relational DB, it contains documents not tables. It has json presentation of objects, and when a field=null, it disappears. Maybe my explanation is a bit twisted, please correct me if I'm wrong.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文