How to delete items in MongoRepository using query

2020-05-25 06:28发布

问题:

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.

回答1:

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


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



回答3:

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.



回答4:

Repository:

@Component
public interface SomeRepository extends MongoRepository<SomeObject, String> {

    @Query("{ '_id' : ?0 }")
    SomeObject findById(String _id);
}

Code in some class:

@Autowired
private SomeRepository pRepo;

public void delete(String id) {

    pRepo.delete(pRepo.findById(id));
}


回答5:

Try this, it's work for me.

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


回答6:

How to delete a list of ids in the query ?

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