How to delete items in MongoRepository using query annotation?

35,243

Solution 1

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

Solution 2

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.

Solution 3

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);

Solution 4

How to delete a list of ids in the query ?

@Query(value="{idList : $0}", delete = true)

Solution 5

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.

Share:
35,243

Related videos on Youtube

paul
Author by

paul

https://github.com/politrons/reactive

Updated on October 25, 2020

Comments

  • paul
    paul over 3 years

    I'm using Spring Data with MongoDB using MongoRepository.

    I was wondering if it is possible do a delete by filter using query annotation. I have been looking here and google and I cannot find any documentation.

  • Agoston Horvath
    Agoston Horvath over 9 years
    This will result in 2 mongo queries instead of a single delete(criteria) one.
  • Rob Baily
    Rob Baily about 8 years
    This appears to be the latest as of now so I think this should be the top answer.
  • andreyro
    andreyro over 7 years
    Thanks!, Worked for me. (was missing "delete = true")
  • andreyro
    andreyro over 7 years
    @Query works now for deleting. You add @Query(value = "{id: ?0}", delete = true) as Marcelo Pasut mentioned in answer.
  • Jagrut Dalwadi
    Jagrut Dalwadi almost 6 years
    you can also use @DeleteQuery which does not require explicitly delete=true setting.
  • Yunnosch
    Yunnosch about 4 years
    I recommend against answers in the shape of rethoric questions and against quoting questions in answers. Both puts the answer at risk of being mistaken for a question (at leat by lazy readers). Instead provide an explanation of how your solution works and why it solves the problem described in the question. That is anyway more appreciated here, because it also helps fighting the misconception that StackOverflow is a free codewriting service.