skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. You could use simply

    @Query(value = "{}", delete = true)
    void deleteAgeField();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search