How to delete items in MongoRepository using query annotation?

@Query(value="{'id' : $0}", delete = true)
public Person deleteById (String id);

Try this, it's work for me.

@Repository
public interface DepartmentDao extends MongoRepository<Department, String> {
    @DeleteQuery
    void deleteByDepartment(String department);
}

OR

@Query(value="{'_id' : ?0}", delete = true)
public void deleteById(String id);

Unfortunately spring data doesn't provides any method to delete documents based on a query. And the @Query annotation is only for find documents.

What you could do is implement a custom repository that deletes documents based on what you want.


Maybe you can use repository delete queries. Here is an example from documentation:

public interface PersonRepository extends MongoRepository<Person, String> {
  List <Person> deleteByLastname(String lastname);

  Long deletePersonByLastname(String lastname);         
}

Using return type List will retrieve and return all matching documents before actually deleting them. A numeric return type directly removes the matching documents returning the total number of documents removed.