View a markdown version of this page

$facet - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$facet

バージョン 8.0.2 の新機能。

Amazon DocumentDB の$facet集約ステージは、同じ入力ドキュメントセットの 1 つのステージ内で複数の集約パイプラインを処理します。各出力フィールドは独自のパイプラインを定義し、すべてのパイプラインは同じ入力ドキュメントを受け取ります。これにより、複数の個別のクエリでコレクションを実行するのではなく、カウント、グループ化、サマリー統計など、複数の独立した集計を 1 つのクエリで計算できます。

各サブパイプラインは個別に実行され、対応する出力フィールドに保存されているドキュメントの配列を生成します。サブパイプラインは状態を共有しないため、あるパイプラインの出力は別のパイプラインには影響しません。

[Syntax] (構文)

{ $facet: { <outputField1>: [ <stage1>, <stage2>, ... ], <outputField2>: [ <stage1>, <stage2>, ... ], ... } }

パラメータ

  • outputField (必須): 関連付けられた集約パイプラインの結果配列を保持する出力フィールドの名前。1 つ以上の出力フィールドを指定できます。各出力フィールドは、入力ドキュメントに適用される集約パイプラインステージの配列にマッピングされます。

出力

$facet ステージは 1 つのドキュメントを返します。指定する各出力フィールドには、対応するサブパイプラインによって生成されたドキュメントの配列が含まれています。

制限事項

  • $facet サブパイプラインには、、$changeStream、 $facet (ネストは許可されません)$collStats、$geoNear、、$indexStats、、$listSearchIndexes$merge、$out、$planCacheStats$search$searchMeta、、 の各ステージを含めることはできません$vectorSearch。

  • $facet ステージが返すドキュメントは、16 MB の BSON ドキュメントサイズ制限内にとどまる必要があります。

  • $sort ステージの前に来る$facetステージでは$first、$facet境界全体に順序を適用する必要がある場合に、、$last$push$firstN$lastN、、、、または $bucketAutoステージで順序の影響を受けやすいアキュムレータ ($group、$bucket、、、または $mergeObjects) の順序を判断できません。これは、グループ化ステージが$facetサブパイプライン内にあるか、$facetステージの後かにかかわらず適用されます。この場合、Amazon DocumentDB はパイプラインを実行する代わりにエラーを返します。このようなアキュムレータを注文するには、グループ化$sortステージの直前に、$facetサブパイプライン内にステージを配置します。、、$sum、 $min $maxなどの順序に依存しないアキュムレータ$countは影響を受けません。

例 (MongoDB シェル)

次の例は、 $facetステージを使用して、1 つのクエリで同じ売上データに対する複数の集計を計算する方法を示しています。

サンプルドキュメントを作成する

db.sales.insertMany([ { item: "abc", price: 10, quantity: 2, date: new Date("2020-09-01") }, { item: "def", price: 20, quantity: 1, date: new Date("2020-10-01") }, { item: "ghi", price: 5, quantity: 3, date: new Date("2020-11-01") }, { item: "jkl", price: 15, quantity: 2, date: new Date("2020-12-01") }, { item: "abc", price: 25, quantity: 1, date: new Date("2021-01-01") } ]);

クエリの例

次のコマンドは、 $facetを使用して、1 つのステージで項目あたりの販売数の合計、全体的な価格統計、およびドキュメント数の合計を計算します。

db.sales.aggregate([ { $facet: { "totalByItem": [ { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } } ], "priceStats": [ { $group: { _id: null, avgPrice: { $avg: "$price" }, maxPrice: { $max: "$price" } } } ], "documentCount": [ { $count: "total" } ] } } ])

出力

このコマンドは、以下の出力を返します。

[ { totalByItem: [ { _id: "abc", totalQuantity: 3 }, { _id: "def", totalQuantity: 1 }, { _id: "ghi", totalQuantity: 3 }, { _id: "jkl", totalQuantity: 2 } ], priceStats: [ { _id: null, avgPrice: 15, maxPrice: 25 } ], documentCount: [ { total: 5 } ] } ]

コードの例

$facet コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const sales = db.collection('sales'); const result = await sales.aggregate([ { $facet: { "totalByItem": [ { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } } ], "priceStats": [ { $group: { _id: null, avgPrice: { $avg: "$price" }, maxPrice: { $max: "$price" } } } ], "documentCount": [ { $count: "total" } ] } } ]).toArray(); console.log(result); client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] sales = db['sales'] result = list(sales.aggregate([ { '$facet': { 'totalByItem': [ {'$group': {'_id': '$item', 'totalQuantity': {'$sum': '$quantity'}}} ], 'priceStats': [ {'$group': {'_id': None, 'avgPrice': {'$avg': '$price'}, 'maxPrice': {'$max': '$price'}}} ], 'documentCount': [ {'$count': 'total'} ] } } ])) print(result) client.close() example()