개요
이 가이드 에서는 MongoDB 컬렉션의 문서 수를 계산하는 방법을 학습 수 있습니다. Node.js 운전자 컬렉션 의 문서 수를 계산하는 두 가지 방법을 제공합니다.
컬렉션 .countDocuments() 는 지정된 쿼리 와 일치하는 컬렉션 의 문서 수를 반환합니다. 빈 쿼리 문서 지정하면
countDocuments()는 컬렉션 의 총 문서 수를 반환합니다.collection.estimatedDocumentCount()는 컬렉션 메타데이터를 기반으로 컬렉션의 문서 수에 대한 추정치를 반환합니다.
estimatedDocumentCount() , 추정 시 collection을 스캔하는 대신 collection의 메타데이터를 사용하므로 countDocuments()보다 빠릅니다. 반면 countDocuments()은 반환하는 데 시간이 더 오래 걸리지만 문서 수를 정확하게 계산하고 필터 지정을 지원합니다. 워크로드에 적합한 방법을 선택하세요.
개수를 계산할 문서를 지정하기 위해 countDocuments()는 쿼리 매개변수를 허용합니다. countDocuments() 지정된 쿼리와 일치하는 문서의 수를 계산합니다.
countDocuments() 그리고 estimatedDocumentCount()는 메소드 실행에 영향을 미치는 선택적 설정을 지원합니다. 자세한 내용은 각 메소드에 대한 참고 문서를 참조하세요.
팁
컬렉션 스캔을 피함으로써 countDocuments() 명령을 사용하여 컬렉션의 총 문서 수를 반환할 때 성능을 향상시킬 수 있습니다. 이렇게 하려면 힌트 를 사용하여 _id 필드에 내장된 인덱스를 활용하세요. 빈 쿼리 매개 변수를 사용하여 countDocuments()를 호출할 때만 이 방법을 사용하세요.
collection.countDocuments({}).hint("_id");
countDocuments() 예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoDB 에 연결 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기단계에 따라 MongoDB Atlas 의 프리 티어 에서 데이터베이스 에 로드할 수 있습니다.
참고
타입스크립트 (Typescript) 관련 기능 없음
다음 코드 예시 JavaScript 사용합니다. 이 사용 사례 와 관련된 운전자 의 타입스크립트 (Typescript) 특정 기능은 없습니다.
다음 예시 sample_mflix 데이터베이스 의 movies 컬렉션 에 있는 문서 수를 추정한 다음 countries 필드 에 Canada 이 있는 movies 컬렉션 의 문서 수에 대한 정확한 개수를 반환합니다.
1 // Count documents in a collection 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Print the estimate of the number of documents in the 16 "movies" collection */ 17 const estimate = await movies.estimatedDocumentCount(); 18 console.log(`Estimated number of documents in the movies collection: ${estimate}`); 19 20 /* Print the number of documents in the "movies" collection that 21 match the specified query */ 22 const query = { countries: "Canada" }; 23 const countCanada = await movies.countDocuments(query); 24 console.log(`Number of movies from Canada: ${countCanada}`); 25 } finally { 26 // Close the connection after the operations complete 27 await client.close(); 28 } 29 } 30 // Run the program and print any thrown exceptions 31 run().catch(console.dir);
앞의 샘플 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349
API 문서
이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.