programing

쿼리 주석을 사용하여 MongoRepository에서 항목을 삭제하는 방법은 무엇입니까?

linuxpc 2023. 6. 25. 18:31
반응형

쿼리 주석을 사용하여 MongoRepository에서 항목을 삭제하는 방법은 무엇입니까?

저는 MongoRepository를 사용하여 Spring Data를 MongoDB와 함께 사용하고 있습니다.

쿼리 주석을 이용하여 필터로 삭제가 가능한지 궁금합니다.제가 여기서 구글 검색을 해봤는데 문서를 찾을 수가 없습니다.

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

리포지토리 삭제 쿼리를 사용할 수 있습니다.다음은 설명서의 예입니다.

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

  Long deletePersonByLastname(String lastname);         
}

반환 유형 목록을 사용하면 일치하는 모든 문서를 검색하고 실제로 삭제하기 전에 반환합니다.숫자 반환 유형은 제거된 총 문서 수를 반환하는 일치 문서를 직접 제거합니다.

이것 좀 먹어봐요, 저한테는 일이에요.

@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);

안타깝게도 스프링 데이터는 쿼리를 기반으로 문서를 삭제할 수 있는 방법을 제공하지 않습니다.그리고.@Query주석은 문서 찾기에만 사용됩니다.

원하는 내용에 따라 문서를 삭제하는 사용자 정의 리포지토리를 구현할 수 있습니다.

쿼리에서 ID 목록을 삭제하는 방법은 무엇입니까?

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

리포지토리:

@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));
}
@Repository
public interface DepartmentDao extends MongoRepository<Department, String> {
    void deleteByDepartment(String department);
}

깨끗하고 짧습니다.

아래 코드 조각 표시는 planId 필드가 목록에 제공된 planId와 일치하는 모든 문서를 계획 모음에서 삭제합니다.

@Repository
public interface PlanRepository extends MongoRepository<Plan, String> {

    @Query(value = "{ 'planId' : { $in : ?0 } }", delete = true)
  void deleteAllByPlanIdIn(List<String> planIds);
}

설명:

  • 우리는 사용할 수 있습니다.@QuerySpring의 MongoDB 데이터 저장소에 대한 사용자 지정 쿼리를 정의하는 주석

  • 더 "valueattribute는 MongoDB 쿼리를 JSON과 유사한 구문으로 지정합니다.

  • "planId조회 중인 계획 문서의 필드입니다.

  • "{ $in : ?0 }는 planId 필드의 값이 제공된 planId 목록(")에 있는지 확인하는 쿼리 연산자입니다.?0메서드의 첫 번째 매개 변수인 planId)의 목록을 나타냅니다.

  • "delete = true쿼리를 삭제할 예정임을 나타내는 데 사용됩니다.

언급URL : https://stackoverflow.com/questions/17484153/how-to-delete-items-in-mongorepository-using-query-annotation

반응형