문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Java 동기화 드라이버

문서 수 계산

컬렉션의 문서 수를 계산하기 위해 호출할 수 있는 MongoCollection 클래스에는 두 가지 인스턴스 메서드가 있습니다.

  • countDocuments() 컬렉션에서 지정된 쿼리와 일치하는 문서 수를 반환합니다. 빈 쿼리 필터를 지정하면 메서드는 컬렉션에 있는 총 문서 수를 반환합니다.

  • estimatedDocumentCount() 컬렉션 메타데이터를 기반으로 컬렉션 내 문서 수의 추정치를 반환합니다. 이 메서드를 사용할 때는 쿼리를 지정할 수 없습니다.

estimatedDocumentCount() 메서드는 전체 컬렉션을 스캔하는 대신 컬렉션의 메타데이터를 사용하기 때문에 countDocuments() 메서드보다 빠릅니다. countDocuments() 메서드는 문서 수의 정확한 개수를 반환하고 필터 지정을 지원합니다.

countDocuments() 를 사용하여 컬렉션의 총 문서 수를 반환하는 경우 컬렉션 스캔을 방지하여 성능을 향상시킬 수 있습니다. 이렇게 하려면 힌트 를 사용하여 _id 필드에 내장된 인덱스를 활용합니다. 빈 쿼리 매개변수를 사용하여 countDocuments() 을(를) 호출할 때만 이 기술을 사용합니다.

CountOptions opts = new CountOptions().hintString("_id_");
long numDocuments = collection.countDocuments(new BsonDocument(), opts);

countDocuments() 메서드를 호출할 때 필요에 따라 쿼리 필터 매개변수를 전달할 수 있습니다. estimatedDocumentCount()를 호출할 때는 어떤 매개변수도 전달할 수 없습니다.

중요

Stable API V1 및 MongoDB Server 이슈

"strict" 옵션으로 Stable API V1 을(를) 사용하고 MongoDB Server 버전이 5.0.0~5.0.8(포함)인 경우 estimatedDocumentCount() 에 대한 메서드 호출 시 서버 버그로 인해 오류가 발생할 수 있습니다.

이 문제를 방지하려면 MongoDB Server 5.0.9로 업그레이드하거나 Stable API "strict" 옵션을 false로 설정합니다.

호출 동작을 지정하기 위해 다음 메서드 중 하나에 선택적 매개변수를 전달할 수도 있습니다.

메서드
선택적 매개변수 클래스
설명
countDocuments()
CountOptions
limit() 메서드를 사용하여 계산할 최대 문서 수를 지정하거나 maxTime() 메서드를 사용하여 최대 실행 시간을 지정할 수 있습니다.
estimatedDocumentCount()
EstimatedDocumentCountOptions
maxTime() 메서드를 사용하여 최대 실행 시간을 지정할 수 있습니다.

두 메서드 모두 일치하는 문서 수를 long 기본으로 반환합니다.

다음 예는 sample_mflix 데이터베이스의 movies 컬렉션에 있는 문서 수를 추정하고 countries 필드에 Canada가 있는 movies 컬렉션의 정확한 문서 수를 반환합니다.

참고

이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스 연결에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

// Runs count operations on a collection by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class CountDocuments {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("countries", "Spain");
try {
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);
// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);
// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
}
}
}

앞의 샘플 코드를 실행하면 다음과 같은 출력이 표시됩니다(정확한 숫자는 데이터에 따라 다를 수 있음).

Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

레거시 API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 API 설명서를 참조하세요.

← 변화를 주시하세요