개요
이 가이드에서는 컬렉션의 문서 수에 대한 개의 정확한 예상 개수를 얻는 방법에 대해 알아볼 수 있습니다.
샘플 데이터
이 섹션의 예시에서는 다음 구조체를 Tea
컬렉션에 있는 문서의 모델로 tea
사용합니다.
type Tea struct { Type string Rating int32 }
이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db
데이터베이스의 tea
컬렉션에 로드합니다.
coll := client.Database("db").Collection("tea") docs := []interface{}{ Tea{Type: "Masala", Rating: 10}, Tea{Type: "Matcha", Rating: 7}, Tea{Type: "Assam", Rating: 4}, Tea{Type: "Oolong", Rating: 9}, Tea{Type: "Chrysanthemum", Rating: 5}, Tea{Type: "Earl Grey", Rating: 8}, Tea{Type: "Jasmine", Rating: 3}, Tea{Type: "English Breakfast", Rating: 6}, Tea{Type: "White Peony", Rating: 4}, } result, err := coll.InsertMany(context.TODO(), docs)
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.
각 문서에는 차의 종류와 등급이 설명되어 있습니다. 이러한 항목은 type
및 rating
필드에 해당합니다.
정확한 카운트
쿼리 필터와 일치하는 문서 수를 계산하려면 CountDocuments()
메서드를 사용합니다. 빈 쿼리 필터를 전달하는 경우 이 메서드는 컬렉션에 있는 총 문서 수를 반환합니다.
팁
CountDocuments()
를 사용하여 컬렉션의 총 문서 수를 반환하면 MongoDB는 컬렉션 스캔을 수행합니다. _id
필드에 내장된 인덱스를 활용하는 힌트를 사용하여 컬렉션 스캔을 피하고 이 메서드의 성능을 향상시킬 수 있습니다. 이 기법은 빈 쿼리 매개 변수로 CountDocuments()
를 호출할 때만 사용합니다.
opts := options.Count().SetHint("_id_") count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts) if err != nil { panic(err) }
동작 수정
CountDocuments()
의 동작을 수정하려면 CountOptions
유형을 전달하세요. 옵션을 지정하지 않으면 드라이버는 기본값을 사용합니다.
CountOptions
유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.
메서드 | 설명 |
---|---|
| The type of language collation to use when sorting results. Default: nil |
| The index to use to scan for documents to count. Default: nil |
| The maximum number of documents to count. Default: 0 |
| The number of documents to skip before counting. Default: 0 |
예시
다음 예에서는 rating
이 6
보다 작은 문서 수를 계산합니다.
filter := bson.D{{"rating", bson.D{{"$lt", 6}}}} count, err := coll.CountDocuments(context.TODO(), filter) if err != nil { panic(err) } fmt.Printf("Number of documents with a rating less than six: %d\n", count)
Number of documents with a rating less than six: 4
집계
집계 파이프라인에 있는 문서 수를 계산하는 $count 단계를 포함할 수도 있습니다.
예시
다음 예시에서는 다음 작업을 수행합니다:
rating
필드의 값이5
보다 큰 문서 수를 계산합니다.counted_documents
필드에 개수를 할당합니다.
matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}} countStage := bson.D{{"$count", "counted_documents"}} cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, countStage}) if err != nil { panic(err) } var results []bson.D if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
[{counted_documents 5}]
예상 개수
컬렉션의 문서 수를 추정하려면 EstimatedDocumentCount()
메서드를 사용합니다.
참고
0}EstimatedDocumentCount()
메서드는 전체 컬렉션을 스캔하는 대신 컬렉션의 메타데이터를 사용하기 때문에 CountDocuments()
메서드보다 빠릅니다.
동작 수정
EstimatedDocumentCountOptions
유형을 전달하여 EstimatedDocumentCount()
의 동작을 수정할 수 있습니다. 옵션을 지정하지 않으면 드라이버는 기본값을 사용합니다.
EstimatedDocumentCountOptions
유형을 사용하면 다음 메서드를 사용하여 옵션을 구성할 수 있습니다.
메서드 | 설명 |
---|---|
| Sets a comment to attach to the count operation. Default: nil |
예시
다음 예는 tea
컬렉션의 문서 수를 추정하는 예입니다:
count, err := coll.EstimatedDocumentCount(context.TODO()) if err != nil { panic(err) } fmt.Printf("Estimated number of documents in the tea collection: %d\n", count)
Estimated number of documents in the tea collection: 9
문서 수 예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants
데이터베이스의 restaurants
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
이 예시 restaurants
컬렉션 에 대해 다음을 수행합니다.
컬렉션의 문서 수 추정
cuisine
필드 의 값이"American"
인 문서 수를 계산합니다.
// Counts documents in a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/usage-examples/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Specifies a filter to match documents where the "cuisine" field // has a value of "American" filter := bson.D{{"cuisine", "American"}} // Retrieves and prints the estimated number of documents in the collection estCount, estCountErr := coll.EstimatedDocumentCount(context.TODO()) if estCountErr != nil { panic(estCountErr) } // Retrieves and prints the number of matching documents in the collection count, err := coll.CountDocuments(context.TODO(), filter) if err != nil { panic(err) } // When you run this file, it should print: // Estimated number of documents in the movies collection: 25359 // Number of restaurants with American cuisine: 6183 fmt.Printf("Estimated number of documents in the restaurants collection: %d\n", estCount) fmt.Printf("Number of restaurants with American cuisine: %d\n", count) }
Estimated number of documents in the restaurants collection: 25359 Number of restaurants with American cuisine: 6183
추가 정보
언급된 작업에 대해 자세히 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.