集計
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 |
制限
集計操作には制限があります。 集計操作を実行するときは、次の点に注意してください。
返されたドキュメントは、 16メガバイトの BSON ドキュメント サイズ制限に違反していない必要があります。
パイプライン ステージには、デフォルトで100 MB のメモリ制限があります。 必要に応じて、 allowDiskUse を使用してこの制限を超えることができます 使用して複数のドキュメントを挿入できます。
$graphLookupステージは100メガバイトという厳格なメモリ制限があり、
allowDiskUse
を無視します。
例
このセクションの例を実行するには、次のスニペットを使用してサンプルデータをtea.menu
コレクションにロードします。
coll := client.Database("tea").Collection("menu") docs := []interface{}{ bson.D{{"type", "Masala"}, {"category", "black"}, {"toppings", bson.A{"ginger", "pumpkin spice", "cinnomon"}}, {"price", 6.75}}, bson.D{{"type", "Gyokuro"}, {"category", "green"}, {"toppings", bson.A{"berries", "milk foam"}}, {"price", 5.65}}, bson.D{{"type", "English Breakfast"}, {"category", "black"}, {"toppings", bson.A{"whipped cream", "honey"}}, {"price", 5.75}}, bson.D{{"type", "Sencha"}, {"category", "green"}, {"toppings", bson.A{"lemon", "whipped cream"}}, {"price", 5.15}}, bson.D{{"type", "Assam"}, {"category", "black"}, {"toppings", bson.A{"milk foam", "honey", "berries"}}, {"price", 5.65}}, bson.D{{"type", "Matcha"}, {"category", "green"}, {"toppings", bson.A{"whipped cream", "honey"}}, {"price", 6.45}}, bson.D{{"type", "Earl Grey"}, {"category", "black"}, {"toppings", bson.A{"milk foam", "pumpkin spice"}}, {"price", 6.15}}, bson.D{{"type", "Hojicha"}, {"category", "green"}, {"toppings", bson.A{"lemon", "ginger", "milk foam"}}, {"price", 5.55}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) }
各ドキュメントは、店舗のメニューのお茶を表しています。 お茶の種類、追加できるトッピング、価格に関する情報が記載されています。
平均評価
次の例では、各お茶の平均評価と評価数を計算して表示しています。
集計パイプラインは、 $group
ステージを使用してドキュメントをcategory
フィールドでグループ化し、 $avg
式演算子を使用して平均を計算し、 $sum
式演算子を使用してドキュメントの数を数えます。
// create the stage groupStage := bson.D{ {"$group", bson.D{ {"_id", "$category"}, {"average_price", bson.D{ {"$avg", "$price"}, }}, {"type_total", bson.D{ {"$sum", 1}, }}, }}} // pass the stage into a pipeline // pass the pipeline as the second paramter in the Aggregate() method cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{groupStage}) if err != nil { panic(err) } // display the results 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: $%v \n", result["_id"], result["average_price"]) fmt.Printf("Amount of %v tea: %v \n\n", result["_id"], result["type_total"]) }
結果のフィールドを省略する
次の例では、ミルクフォームをトッピングできるドキュメントを照合し、最も安価なオプションを 2 つ挙げています。
集計パイプラインには、次のステージが含まれています。
$match
ステージtoppings
に「milk foam」が含まれるドキュメントを照合する$unset
_id
とcategory
フィールドを省略するステージ$sort
price
とtoppings
を昇順に並べ替えるステージ$limit
最初の 2 つのドキュメントを表示するステージ
// create the stages 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}} // pass the stage into a pipeline // pass the pipeline as the second paramter in the Aggregate() method cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage}) if err != nil { panic(err) } // display the results var results []bson.M 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"], result["toppings"], result["price"]) }
詳細情報
記載されている用語について詳しくは、次のガイドを参照してください。
集計の例をさらに見るには、次のガイドを参照してください。
Aggregate()
メソッドとその動作について詳しくは、「データを検索する」を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。