Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go Driver
/ /

ドキュメントをカウント

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

このセクションの例では、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 タイプでは、次の方法でオプションを設定できます。

方式
説明

SetCollation()

The type of language collation to use when sorting results.
Default: nil

SetHint()

The index to use to scan for documents to count.
Default: nil

SetLimit()

The maximum number of documents to count.
Default: 0

SetSkip()

The number of documents to skip before counting.
Default: 0

次の例では、rating6 より小さいドキュメントの数をカウントします。

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 タイプでは、以下の方法を使用してオプションを設定できます。

方式
説明

SetComment()

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 ドキュメントを参照してください。

戻る

返すフィールドを指定する

項目一覧