AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

ドキュメントをカウントするメソッドの例

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ドキュメントがあります

注意

ドキュメントの正確な数は、データセットによって異なる場合があります。

ドキュメントをカウントする方法の詳細については、「 ドキュメントをカウントする 」を参照してください。

このページを評価