2013-07-05 35 views

回答

6
@Query(value="{id : $0}", delete = true) 
public Person deleteBy 
+0

謝謝!,爲我工作。 (缺少「delete = true」) – andreyro

3

不幸的是,spring數據並沒有提供任何方法來刪除基於查詢的文檔。而@Query註釋僅用於查找文檔。

你可以做的是實現一個custom repository,根據你的需要刪除文檔。

+0

i'll看看謝謝! – paul

+1

@Query現在可用於刪除。您添加@Query(value =「{id:?0}」,delete = true),正如Marcelo Pasut在答案中提到的那樣。 – andreyro

7

也許你可以使用存儲庫刪除查詢。下面是documentation一個例子:

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

    Long deletePersonByLastname(String lastname);   
} 

使用返回類型列表將檢索和實際刪除它們之前返回所有匹配的文件。數字返回類型直接刪除返回已刪除文檔總數的匹配文檔。

+0

這似乎是最新的截至目前,所以我認爲這應該是最好的答案。 –

0

庫:

@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)); 
} 
+2

這將導致2個mongo查詢而不是單個刪除(標準)。 –