문서 메뉴
문서 홈
/ / /
Java 동기화 드라이버
/ / /

반환되는 결과 수 제한

이 페이지의 내용

  • 개요
  • 한도 지정
  • 건너뛰기와 제한 결합

이 가이드에서는 MongoDB Java 드라이버를 사용하여 읽기 작업에서 반환되는 결과 수를 제한하는 방법을 배울 수 있습니다.

읽기 작업에서 반환하는 문서 수를 제한하려면 limit() 를 사용합니다. 이 인스턴스 메서드는 읽기 작업이 반환할 수 있는 최대 문서 수를 지정합니다. 지정된 제한에 도달할 만큼 문서가 충분하지 않은 경우 더 적은 수를 반환할 수 있습니다. limit()skip() 인스턴스 메서드와 함께 사용하면 건너뛰기가 먼저 적용되고 건너뛰기 후 남은 문서에만 제한이 적용됩니다. skip() 메서드에 대한 자세한 내용은반환된 문서 건너뛰기에대한 가이드를 참조하세요.

다음 예제에서는 각각 컬렉션에 데이터를 삽입하는 방법, limit()을 사용하여 반환되는 문서 수를 제한하는 방법, limit()skip()과 결합하여 쿼리에서 반환되는 결과를 더욱 좁히는 방법을 보여 줍니다.

다음 작업은 책을 나타내는 문서를 컬렉션에 삽입합니다.

collection.insertMany(Arrays.asList(
new Document().append("_id", 1)
.append("title", "The Brothers Karamazov").append("length", 824)
.append("author", "Dostoyevsky"),
new Document().append("_id", 2)
.append("title", "Les Misérables").append("length", 1462).append("author", "Hugo"),
new Document().append("_id", 3)
.append("title", "Atlas Shrugged").append("length", 1088).append("author", "Rand"),
new Document().append("_id", 4)
.append("title", "Infinite Jest").append("length", 1104).append("author", "Wallace"),
new Document().append("_id", 5)
.append("title", "Cryptonomicon").append("length", 918).append("author", "Stephenson"),
new Document().append("_id", 6)
.append("title", "A Dance with Dragons").append("length", 1104)
.append("author", "Martin")
));

다음 예에서는 collection을 쿼리하여 가장 긴 책 3권을 반환합니다. 먼저 모든 문서를 쿼리와 일치시킨 다음 length 필드를 정렬하여 길이가 긴 책을 길이가 짧은 책보다 먼저 반환합니다. 마지막으로 반환 값을 3매의 문서로 제한합니다.

import com.mongodb.client.*;
import org.bson.Document;
import static com.mongodb.client.model.Sorts.descending;
// ...
// define a cursor that will return the first 3 sorted items
MongoCursor<Document> cursor = collection.find()
.sort(descending("length"))
.limit(3)
.iterator();
// print out items
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
// close the cursor
finally {
cursor.close();
}

앞의 코드 예제에서는 길이별로 정렬된 다음의 문서 서 개를 인쇄합니다.

Document{{_id=2, title=Les Misérables, author=Hugo, length=1462}}
Document{{_id=6, title=A Dance with Dragons, author=Martin, length=1104}}
Document{{_id=4, title=Infinite Jest, author=Wallace, length=1104}}

limit()sort()를 호출하는 순서는 중요하지 않습니다. 드라이버가 정렬을 먼저 적용하고 그 다음에 제한을 적용하도록 호출의 순서를 변경하기 때문입니다. 다음 두 호출은 동일합니다:

collection.find().sort(descending("length")).limit(3);
collection.find().limit(3).sort(descending("length"));

다음으로 가장 긴 세 권의 책을 보려면 다음의 코드 예와 같이 find() 호출에 skip() 메서드를 추가하세요.

MongoCursor<Document> cursor = collection.find()
.sort(descending("length"))
.limit(3)
.skip(3)
.iterator();

이 작업은 네 번째에서 여섯 번째로 긴 책을 설명하는 문서를 반환합니다.

Document{{_id=3, title=Atlas Shrugged, author=Rand, length=1088}}
Document{{_id=5, title=Cryptonomicon, author=Stephenson, length=918}}
Document{{_id=1, title=The Brothers Karamazov, author=Dostoyevsky, length=824}}

이러한 방식으로 skip()limit()을 결합하여 컬렉션에 페이징을 구현하고 컬렉션의 작은 하위 집합만 한 번에 반환할 수 있습니다.

참고

여러 쿼리에서 안정적인 정렬을 보장하려면 고유 키(예: _id)를 사용하여 정렬해야 합니다. 그렇지 않으면 skip()limit() 호출과 함께 sort() 을 사용할 때 예기치 않은 결과가 발생할 수 있습니다.

예를 들어 다음 데이터를 가정해 보겠습니다.

{ type: "computer", data: "1", serial_no: 235235 }
{ type: "computer", data: "2", serial_no: 235237 }
{ type: "computer", data: "3", serial_no: 235239 }
{ type: "computer", data: "4", serial_no: 235241 }

type 으로만 정렬한 경우 sort() 는 반환 시 동일한 순서를 보장하지 않습니다. sort()skip()limit() 을 추가하면 다양한 쿼리에 대해 다양한 문서가 반환될 수 있습니다. 이 경우 data 또는 serial_no 기준으로 정렬하면 둘 다 고유 키이므로 안정적인 정렬이 보장됩니다.

이 가이드에 언급된 메서드 및 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.

  • FindIterable

  • MongoIterable

  • MongoCursor

  • find()

← 반환된 결과 건너뛰기