Skip to content

6.문서 조회(QUERY)#

FindOperation (Fluent API)#

find(), findByCond(), findByJsonPath() 메서드는 FindOperation 객체를 반환한다. 이 객체를 사용해 정렬, 페이징 등을 체이닝 방식으로 설정할 수 있다.

메서드#

메서드 설명
skip(int size) 앞에서 N개 건너뛰기
limit(int limit) 최대 반환 개수
sort(AltibaseDocument sort) 정렬 (1: 오름차순, -1: 내림차순)
execute() 쿼리 실행

예제: 페이징 조회#

try (AltibaseCollection books = db.getCollection("books")) {
    // 페이지 2 조회 (페이지당 10개)
    int page = 2;
    int pageSize = 10;

    try (DocResult results = books.find()
            .skip((page - 1) * pageSize)  // 10개 건너뛰기
            .limit(pageSize)               // 10개만 조회
            .execute()) {

        for (AltibaseDocument doc : results) {
            System.out.println(doc.toJson());
        }
    }
}

예제: 정렬 조회

try (AltibaseCollection books = db.getCollection("books")) {
    //1. 정렬 조건 정의(-1: 내림차순, 1:오름 차순)
    // 출판년도는 내림차순으로, 제목은 오름차순으로 설정.
    AltibaseDocument sortSpec = AltibaseDocument.parse(
        "{\"year\": -1, \"title\": 1}"
    );

    // 2. Fluent API를 사용한 쿼리 빌딩 및 실행
    // find()로 시작하여 옵션을 체이닝한 후, 마지막에 execute()를 호출하여 결과를 가져옴.
    try (DocResult results = books.find()
            .sort(sortSpec)
            .limit(20)
            .execute()) {

     // 3. 결과 출력
        for (AltibaseDocument doc : results) {
            System.out.println(doc.getString("title") + " (" + doc.getInteger("year") + ")");
        }
    }
}

예제: 조건 + 정렬 +페이징

try (AltibaseCollection products = db.getCollection("products")) {
    // 가격 10000원 이상, 가격순 정렬, 상위 5개
    AltibaseDocument filter = AltibaseDocument.parse("{\"price\": {\"$gte\": 10000}}");
    AltibaseDocument sort = AltibaseDocument.parse("{\"price\": 1}");

    try (DocResult results = products.findByCond(filter)
            .sort(sort)
            .limit(5)
            .execute()) {

        List<AltibaseDocument> topProducts = results.fetchAll();
        topProducts.forEach(p -> System.out.println(p.toJson()));
    }
}

DocResult#

DocResult는 조회 쿼리 실행 시 반환되는 결과 집합 객체이다.

메서드#

메서드 리턴 타입 설명
hasNext() boolean 다음 읽을 문서가 존재하는지 여부를 확인한다.
next() AltibaseDocument 다음 문서를 반환한다.
fetchAll() List\ 전체 결과를 메모리에 로드하여 리스트 형태로 반환한다.
rewind() void 커서의 위치를 결과 집합의 처음으로 되돌린다.
count() long 문서의 개수를 반환한다.

데이터 처리 방식#

DocResult는 데이터의 크기와 활용 목적에 따라 스트리밍과 캐싱 두가지 방식으로 사용할 수 있다.

스트리밍 방식#

데이터를 한 건씩 가져와 처리하는 방식으로 메모리 사용을 최소화할 수 있다. 대용량 데이터를 처리할 때 효율적이다.

캐싱 방식#

전체 데이터를 메모리에 적재하여 사용하는 방식이다. 데이터를 여러번 반복해서 확인해야 할 때 유용하다. fetchAll()로 리스트화 하거나, rewind()를 통회 처음부터 다시 순회할 수 있다.

예제: 스트리밍 방식(메모리 효율)#

try (DocResult results = collection.find().execute()) {
    while (results.hasNext()) {
        AltibaseDocument doc = results.next();
        // 한 번에 하나씩 처리
    }
}

예제: 캐싱 방식(재사용 가능)#

try (DocResult results = collection.find().execute()) {
    // 모든 결과를 메모리에 로드
    List<AltibaseDocument> all = results.fetchAll();

    // 다시 처음부터 순회
    results.rewind();
    for (AltibaseDocument doc : results) {
        // 캐시된 데이터 순회
    }
}

InsertResult#

InsertResult는 문서 삽입(insert) 연산의 결과를 나타내는 객체이다.

메서드#

메서드 리턴 타입 설명
getAffectedDocCount() long 삽입 연산으로 영향을 받은 문서 수를 반환한다.
getKeyValue() Object 삽입된 문서의 키 값을 반환한다.
getKeyType() Class<?> 삽입된 키의 Java 타입 정보를 반환한다.
getIntegerKey() Integer 삽입된 키를 Integer 타입으로 반환한다.
getStringKey() String 삽입된 키를 String 타입으로 반환한다.
getLongKey() Long 삽입된 키를 Long 타입으로 반환한다.
getShortKey() Short 삽입된 키를 Short 타입으로 반환한다.

예제#

AltibaseDocument doc = books.createDocument("{\"title\": \"1984\"}");
InsertResult result = books.insertOne(doc);

System.out.println("영향받은 문서 수: " + result.getAffectedDocCount());
System.out.println("생성된 키: " + result.getStringKey());

UpdateResult#

UpdateResult는 문서 수정(update), 교체(replace), 삭제(delete) 연산의 결과를 나타내는 객체이다.

메서드#

메서드 리턴 타입 설명
getAffectedDocCount() long 연산으로 영향을 받은 문서 수를 반환한다.

예제#

AltibaseDocument filter = AltibaseDocument.parse("{\"status\": \"inactive\"}");
UpdateResult result = users.deleteMany(filter);
System.out.println("삭제된 문서 수: " + result.getAffectedDocCount());