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 g
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));
}
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);
How to delete a list of ids in the query ?
@Query(value="{idList : $0}", delete = true)
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.
@Query(value="{'id' : $0}", delete = true)
public Person deleteById (String id);
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.