How to delete items in MongoRepository using query annotation?

后端 未结 6 1176
北海茫月
北海茫月 2021-02-05 06:03

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

相关标签:
6条回答
  • 2021-02-05 06:46

    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));
    }
    
    0 讨论(0)
  • 2021-02-05 06:47

    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);
    
    0 讨论(0)
  • 2021-02-05 06:49

    How to delete a list of ids in the query ?

    @Query(value="{idList : $0}", delete = true)
    
    0 讨论(0)
  • 2021-02-05 06:50

    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.

    0 讨论(0)
  • 2021-02-05 06:53
    @Query(value="{'id' : $0}", delete = true)
    public Person deleteById (String id);
    
    0 讨论(0)
  • 2021-02-05 06:53

    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.

    0 讨论(0)
提交回复
热议问题