[英]How to delete a field in all documents of mongodb collection using MongoRepositoty @Query
I have a collection:我有一个收藏:
public class Person {
private String name;
private Integer age;
}
I want to delete field age
in all the documents.我想删除所有文档中的字段
age
。 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:我正在使用 MongoRepositoty 并且一直在尝试编写此方法:
@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.
我发现它与我们在 mongo 控制台中编写查询的方式不同。 For instance, round brackets and double quotes are not allowed here.
例如,此处不允许使用圆括号和双引号。
You could use simply你可以简单地使用
@Query(value = "{}", delete = true)
void deleteAgeField();
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.由于 Mongo 不是关系数据库,它包含文档而不是表。 It has json presentation of objects, and when a field=null, it disappears.
它具有对象的 json 表示,当字段 = null 时,它会消失。 Maybe my explanation is a bit twisted, please correct me if I'm wrong.
可能我的解释有点曲解,如果我错了,请纠正我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.