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

ドキュメントをカウント

このガイドでは、コレクション内のドキュメント数の正確な推定値を取得する方法を学習できます。

このセクションの例では、tea コレクション内のドキュメントのモデルとして次の Tea 構造体を使用します。

type Tea struct { Type string Rating int32}

このガイドの例を実行するには、次のスニペットを使用して、サンプル データを db データベース内の tea コレクションにロードします。

coll := client.Database("db").Collection("tea")docs := []any{ 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)

Tip

存在しないデータベースとコレクション

書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。

各ドキュメントには、茶葉の種類とその格付けが記載されています。これらのアイテムは、type フィールドと rating フィールドに対応します。

クエリフィルターに一致するドキュメントの数をカウントするには、CountDocuments() メソッドを使用します。空のクエリフィルターを渡すと、このメソッドはコレクション内のドキュメントの総数を返します。

Tip

CountDocuments()を使用してコレクション内のドキュメントの合計数を返す場合、MongoDB はコレクションスキャンを実行します。ヒントを使用して_idフィールドの組み込みインデックスを活用することで、コレクションスキャンを回避し、このメソッドのパフォーマンスを向上させることができます。この手法は、空のクエリ パラメーターを使用してCountDocuments()を呼び出す場合にのみ使用してください。

opts := options.Count().SetHint("_id_") count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts)if err != nil { panic(err)}

CountOptions タイプを渡すことで、CountDocuments() の動作を変更することができます。オプションを指定しない場合、ドライバーはデフォルト値を使用します。

CountOptions タイプでは、次の方法でオプションを設定できます。

方式
説明

SetCollation()

結果をソートするときに使用する言語照合のタイプ。
デフォルト: nil

SetHint()

カウントするドキュメントをスキャンするために使用するインデックス。
デフォルト: nil

SetLimit()

カウントするドキュメントの最大数。
デフォルト: 0

SetSkip()

カウントする前にスキップするドキュメントの数。
デフォルト: 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)

また、$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.Dif err = cursor.All(context.TODO(), &results); err != nil { panic(err)}for _, result := range results { fmt.Println(result)}

コレクション内のドキュメントの数を見積もるには、EstimatedDocumentCount() メソッドを使用します。

注意

EstimatedDocumentCount() メソッドは、コレクション全体をスキャンするのではなく、コレクションのメタデータを使用するため、CountDocuments() メソッドよりも高速です。

EstimatedDocumentCountOptions タイプを渡すことで、EstimatedDocumentCount() の動作を変更することができます。オプションを指定しない場合、ドライバーはデフォルト値を使用します。

EstimatedDocumentCountOptions タイプでは、以下の方法を使用してオプションを設定できます。

方式
説明

SetComment()

カウント操作に添付するコメントを設定します。
デフォルト: 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)

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」を参照してください。この例では、Atlas サンプル データセットに含まれる sample_restaurants データベースの restaurants コレクションも使用します。「Atlas スタートガイド」の手順に従って、MongoDB Atlas の無料クラスターのデータベースにロードできます。

この例では、restaurantsコレクションに対して次の操作を実行します。

  • コレクション内のドキュメント数を概算

  • cuisineフィールドの値が "American" であるドキュメントの数をカウントする

// Counts documents in a collection by using the Go driverpackage 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/ja-jp/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)}

上記で説明されている操作の詳細については、次のガイドを参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。