Overview
このガイドでは、コレクション内のドキュメント数のの正確な推定値を取得する方法を学びます。
サンプル データ
このセクションの例では、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)
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
タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
---|---|
| 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()
メソッドを使用します。
注意
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/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) }
Estimated number of documents in the restaurants collection: 25359 Number of restaurants with American cuisine: 6183
詳細情報
上記で説明されている操作の詳細については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。