Docs Menu
Docs Home
/ / /
Go Driver
/

集計

項目一覧

  • Overview
  • 比較操作
  • 制限
  • 詳細情報

このガイドでは、MongoDB Go ドライバーで集計操作を使用する方法を学習できます。

集計操作は、集計パイプラインの仕様に基づいて MongoDB コレクション内のデータを処理します。集計パイプラインは、1 つ以上の ステージ で構成されます。各ステージでは、式演算子に基づいて演算を実行します。ドライバーは集計パイプラインを実行した後、集計された結果を返します。

集計操作は自動車工場と同様に機能します。自動車工場には組立ラインがあります。組立ラインには、特定のタスクを実行するための特殊なツールを備えた組立ステーションがあります。車を製造するには、原材料の部品を工場に送ります。その後、組立ラインで部品を加工し、自動車を組み立てます。

組立ラインは集計パイプラインに似ており、組立ラインの組立ステーションは集計ステージに似ており、専用ツールは式演算子を表し、完成品は集計結果に似ています。

次は、検索(find)操作と集計操作で実行できるタスクをまとめた表です。

検索操作
集計操作
Select what documents to return
Select which fields to return
Sort the results
Limit the results
Count the results
Select what documents to return
Select which fields to return
Sort the results
Limit the results
Count the results
Rename fields
Calculate fields
Summarize data
Group values

集計操作には制限があります。集計操作を実行するときは、次の点に注意してください。

  • 返されたドキュメントは、 BSON ドキュメント サイズの制限である16メガバイトに違反していない必要があります。

  • パイプライン ステージには、デフォルトで 100 メガバイトのメモリ制限があります。必要に応じて、allowDiskUse() メソッドを使用してこの制限を超えることができます。

  • $graphLookup ステージには、100 メガバイトの厳密なメモリ制限があり、allowDiskUse 設定は無視されます。

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

type Tea struct {
Type string
Category string
Toppings []string
Price float32
}

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

coll := client.Database("db").Collection("tea")
docs := []interface{}{
Tea{Type: "Masala", Category: "black", Toppings: []string{"ginger", "pumpkin spice", "cinnamon"}, Price: 6.75},
Tea{Type: "Gyokuro", Category: "green", Toppings: []string{"berries", "milk foam"}, Price: 5.65},
Tea{Type: "English Breakfast", Category: "black", Toppings: []string{"whipped cream", "honey"}, Price: 5.75},
Tea{Type: "Sencha", Category: "green", Toppings: []string{"lemon", "whipped cream"}, Price: 5.15},
Tea{Type: "Assam", Category: "black", Toppings: []string{"milk foam", "honey", "berries"}, Price: 5.65},
Tea{Type: "Matcha", Category: "green", Toppings: []string{"whipped cream", "honey"}, Price: 6.45},
Tea{Type: "Earl Grey", Category: "black", Toppings: []string{"milk foam", "pumpkin spice"}, Price: 6.15},
Tea{Type: "Hojicha", Category: "green", Toppings: []string{"lemon", "ginger", "milk foam"}, Price: 5.55},
}
result, err := coll.InsertMany(context.TODO(), docs)

各ドキュメントには、お茶の種類、利用可能なトッピング、価格に関する情報が記載されています。

次の例では、お茶の各カテゴリーの平均評価と評価数を計算して表示しています。

集計パイプラインは、$group ステージを使用してドキュメントを category フィールドごとにグループ化し、$avg 式演算子を使用して平均を計算し、$sum 式演算子を使用してドキュメントの数を数えます。

groupStage := bson.D{
{"$group", bson.D{
{"_id", "$category"},
{"average_price", bson.D{{"$avg", "$price"}}},
{"type_total", bson.D{{"$sum", 1}}},
}}}
// Performs the aggregation and prints the results
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage})
if err != nil {
panic(err)
}
var results []bson.M
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Average price of %v tea options: $%v \n", result["_id"], result["average_price"])
fmt.Printf("Number of %v tea options: %v \n\n", result["_id"], result["type_total"])
}
Average price of black tea options: $6.075
Number of black tea options: 4
Average price of green tea options: $5.70
Number of green tea options: 4

次の例では、ミルクフォームをトッピングできるドキュメントを照合し、最も安価なオプションを 2 つ挙げています。

集計パイプラインには、次のステージが含まれています。

  • $match toppings フィールドに「ミルクフォーム」が含まれるドキュメントを照合するステージ

  • $unset _idcategory フィールドを省略するステージ

  • $sort pricetoppings を昇順に並べ替えるステージ

  • $limit 最初の 2 つのドキュメントを表示するステージ

matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{{"price", 1}, {"toppings", 1}}}}
limitStage := bson.D{{"$limit", 2}}
// Performs the aggregation and prints the results
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})
if err != nil {
panic(err)
}
var results []Tea
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Printf("Tea: %v \nToppings: %v \nPrice: $%v \n\n", result.Type, strings.Join(result.Toppings, ", "), result.Price)
}
Tea: Hojicha
Toppings: lemon, ginger, milk foam
Price: $5.55
Tea: Gyokuro
Toppings: berries, milk foam
Price: $5.65

記載されている用語について詳しくは、次のガイドを参照してください。

集計の例をさらに見るには、次のガイドを参照してください。

  • Limit

  • スキップ

  • Text

Aggregate() メソッドとその動作について詳しくは、「データを検索する」を参照してください。

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

戻る

CRUD実行の変更