如何使用MongorePositoty @Query删除MongoDB集合的所有文档中的字段
我有一个集合:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地使用
You could use simply
我发现的一种解决方案只是将字段设置为null:
由于Mongo不是关系DB,因此它包含文档而不是表。它具有json的对象表示,当字段= null时,它消失了。也许我的解释有点扭曲,如果我错了,请纠正我。
A solution I've found is simply to set the field to null:
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.