25

我使用 MongoRepository 将 Spring Data 与 MongoDB 一起使用。

我想知道是否可以使用查询注释通过过滤器进行删除。我一直在寻找here和google,但找不到任何文档。

4

6 回答 6

38
@Query(value="{'id' : $0}", delete = true)
public Person deleteById (String id);
于 2015-02-18T12:39:54.937 回答
28

也许您可以使用存储库删除查询。这是文档中的一个示例:

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

  Long deletePersonByLastname(String lastname);         
}

使用返回类型 List 将在实际删除它们之前检索并返回所有匹配的文档。数字返回类型直接删除匹配的文档,返回删除的文档总数。

于 2014-07-01T16:39:05.850 回答
3

不幸的是,spring data 没有提供任何基于查询删除文档的方法。并且@Query注释仅用于查找文档。

您可以做的是实现一个自定义存储库,该存储库根据您的需要删除文档。

于 2013-07-05T13:59:47.440 回答
3

如何删除查询中的 id 列表?

@Query(value="{idList : $0}", delete = true)
于 2020-02-28T07:57:43.433 回答
3

试试这个,它对我有用。

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

或者

@Query(value="{'_id' : ?0}", delete = true)
public void deleteById(String id);
于 2019-02-22T09:54:40.663 回答
1

存储库:

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

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

某些类中的代码:

@Autowired
private SomeRepository pRepo;

public void delete(String id) {

    pRepo.delete(pRepo.findById(id));
}
于 2014-10-17T11:08:04.347 回答