EstimatedDocumentCount()メソッドを使用してコレクション内のドキュメント数の近似値を取得し、 CountDocuments()メソッドを使用してコレクション内の正確なドキュメント数を取得できます。
例
Tip
この例を実行する方法については、「使用例」をお読みください。
次の例では、movies コレクションに対して次の操作を実行します。
コレクション内のドキュメント数を概算
countriesに「中国」が含まれているドキュメントの数をカウントする
coll := client.Database("sample_mflix").Collection("movies")
// Specifies a filter to match documents where the "countries" array// includes a value of "China"filter := bson.D{{"countries", "China"}}
// Retrieves and prints the estimated number of documents in the collectionestCount, estCountErr := coll.EstimatedDocumentCount(context.TODO())if estCountErr != nil { panic(estCountErr)}
// Retrieves and prints the number of documents in the collection// that match the filtercount, err := coll.CountDocuments(context.TODO(), filter)if err != nil { panic(err)}期待される結果
完全な例を実行すると、次の結果が表示されます。
moviesコレクションには約23541のドキュメントがありますmoviesコレクションには、countriesフィールドに「 中国 」を含む303ドキュメントがあります
注意
ドキュメントの正確な数は、データセットによって異なる場合があります。
詳細情報
ドキュメントをカウントする方法の詳細については、「 ドキュメントをカウントする 」を参照してください。