mongodbmongodb-queryspring-mongodbspring-repositories

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. 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.


Solution

  • 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.