简体   繁体   English

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

[英]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.

相关问题 如何在java中删除mongodb集合中的所有文档 - How to delete all documents in mongodb collection in java 如何使用Pentaho中的mongodb删除步骤删除mongodb集合中的文档 - How to delete documents in a mongodb collection using mongodb delete step in Pentaho 查询在 MongoDb 集合中的所有文档中创建一个新字段 - Query to create a new field in all documents in MongoDb collection 如何使用 python mongodb 客户端库 (pymongo) 更新 mongodb 集合中所有文档的字段“类型” - How to update field “type” for all documents in mongodb collection using python mongodb client library (pymongo) 查询删除MongoDB中集合中的最后三个文档 - Query to delete the last three documents in a collection in mongodb 如何为 MongoDB 集合中的所有文档选择单个字段? - How to select a single field for all documents in a MongoDB collection? 使用 MongoDB 聚合删除集合中所有文档的特定字段 - Remove a particular field for all documents in a collection using MongoDB aggregation 使用 mongoDB 中的聚合删除集合中所有文档的特定字段 - Remove a particular field for all documents in a collection using aggregation in mongoDB 如何在Java mongodb驱动程序中使用“ _id”字段查询文档而不使用集合名称? - How to query documents using “_id” field in Java mongodb driver without using the collection name? MongoDB将字段插入集合中的所有文档 - MongoDB Insert Field to all documents in a collection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM