Docs Menu

문서 수 계산

Collection 인스턴스에서 다음 메서드 중 하나를 호출하여 collection의 문서 수를 계산할 수 있습니다.

  • count_documents(): 쿼리 필터하다 와 일치하는 문서 수를 계산합니다. 쿼리 필터 만들기에 학습 보려면 쿼리 지정 가이드 를 참조하세요.

  • 예상_문서_카운트(): 컬렉션 메타데이터를 사용하여 컬렉션의 총 문서 수를 추정합니다.

각 메서드는 개수를 u64 인스턴스로 반환합니다.

참고

count_documents() 메서드에 필터를 전달하지 않으면 MongoDB는 collection의 총 문서 수를 계산합니다.

이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에 있는 문서 수를 계산합니다. 이 예시 estimated_document_count() 메서드를 사용하여 컬렉션 의 총 문서 수를 계산합니다. 그런 다음 count_documents() 예시 를 사용하여 name 필드 의 값에 문자열 "Sunset"가 포함된 문서 수를 계산합니다.

restaurants 컬렉션 의 문서에 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스로 액세스 할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.

  • <Document>: 컬렉션 문서를 BSON 문서로 나타냅니다.

  • <Restaurant>: 컬렉션 문서를 코드 상단에 정의된 Restaurant 구조체의 인스턴스로 나타냅니다.

Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.

use std::env;
use mongodb::{
bson::{ doc, Document },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let ct = my_coll.estimated_document_count().await?;
println!("Number of documents: {}", ct);
let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }).await?;
println!("Number of matching documents: {}", ct);
Ok(())
}
// Your values might differ
Number of documents: 25216
Number of matching documents: 10
use std::env;
use mongodb::{
bson::{ Document, doc },
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let ct = my_coll.estimated_document_count().run()?;
println!("Number of documents: {}", ct);
let ct = my_coll
.count_documents(doc! { "name": doc! { "$regex": "Sunset" } })
.run()?;
println!("Number of matching documents: {}", ct);
Ok(())
}
// Your values might differ
Number of documents: 25216
Number of matching documents: 10