View a markdown version of this page

$maxN - Amazon DocumentDB

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

$maxN

バージョン 8.0.1 から新規。

Amazon DocumentDB の $maxN演算子は N 最大値を返します。$group ステージでアキュムレータとして使用すると、各グループの N 最大値の配列が返されます。配列式演算子として使用すると、配列の最大 N 要素が返されます。

パラメータ

  • input: n最大値を返す配列またはフィールドに解決される式。

  • n: 返す最大値の数を指定する正の整数に解決される式。

動作

配列式演算子の動作

  • よりn小さい値を指定することはできません1。

  • $maxN は、input配列で見つかったnull値をフィルタリングします。

  • 指定された nがinput配列内の要素の数以上である場合、 はinput配列内のすべての要素$maxNを返します。

  • が非配列値にinput解決された場合、集約オペレーションはエラーになります。

  • に数値要素と文字列要素の両方inputが含まれている場合、文字列要素は BSON 比較順序に従って数値要素の前にソートされます。

アキュムレータの動作

  • アキュムレータとして使用する場合、 は定数であるか、 _idの値に依存する正の整数式nである必要があります$group。

  • $maxN は null 値と欠落した値をフィルタリングします。

  • グループに含まれるn要素が より少ない場合、 はグループ内のすべての要素$maxNを返します。

  • $maxN は BSON 比較順序に従って入力データを比較し、適切な出力タイプを決定します。入力データに複数のデータ型が含まれている場合、$maxN出力型は比較順序で最も高い値になります。

出力順序

$maxN は、特定のソート順序で値を返します。特定のソート順序を保証する必要がある場合は、$topN代わりに を使用するか、結果を でラップします$sortArray。

例 (MongoDB シェル)

次の例は、アキュムレータを使用して各サブジェクトの 2 $maxN つの最高スコアを取得する方法を示しています。

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

db.scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]);

クエリの例

db.scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]);

出力

[ { "_id": "math", "highestTwo": [85, 93] }, { "_id": "science", "highestTwo": [88, 90] } ]

式の使用例 (MongoDB シェル)

$maxN 演算子を$projectステージ内の式として使用して、配列フィールドから N 最大の要素を返すこともできます。

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

db.readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]);

クエリの例

db.readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } }} ]);

出力

[ { "_id": 1, "highestThree": [45, 56, 78] }, { "_id": 2, "highestThree": [44, 90, 67] } ]

ウィンドウ演算子の使用例 (MongoDB シェル)

バージョン 8.0.2 の新機能。

$maxN 演算子は、$setWindowFieldsステージのウィンドウ演算子としても使用できます。このコンテキストでは、各ウィンドウのドキュメントの最大n値の配列を返します。output フィールドで 演算子を指定し、オプションでwindowドキュメントを使用してウィンドウの境界を定義します。

注記

でウィンドウ演算子として使用する場合$setWindowFields、 $maxNは 100 MB の中間データに制限されます。この制限を超えるオペレーションはエラーを返します。

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

db.stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]);

クエリの例

次の例では、ドキュメントを でパーティション化しticker、各パーティションを でソートしてhour、パーティションの先頭から現在のドキュメントまでの 2 つの最高価格を返します。

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

出力

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "highestTwoSoFar": [50] }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "highestTwoSoFar": [50, 45] }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "highestTwoSoFar": [60, 50] }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "highestTwoSoFar": [60, 50] }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "highestTwoSoFar": [30] }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "highestTwoSoFar": [35, 30] }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "highestTwoSoFar": [35, 30] } ]

各ドキュメントは、ウィンドウprice内の 2 つの最大値highestTwoSoFarである で拡張されます。出力順序セクションで説明したように、返された配列内の値の順序は保証されません。

コードの例

$maxN 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。次の例は、アキュムレータの使用 ( の場合$group)、式の使用 ( の場合$project)、ウィンドウ演算子の使用 ( の場合) を示しています$setWindowFields。

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); // Accumulator usage: N largest values per group const scores = db.collection('scores'); await scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]); const accumulatorResult = await scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N largest elements from an array field const readings = db.collection('readings'); await readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]); const expressionResult = await readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N largest values over a window in each partition const stockPrices = db.collection('stockPrices'); await stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]); const windowResult = await stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } finally { await 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') try: db = client['test'] # Accumulator usage: N largest values per group scores = db['scores'] scores.insert_many([ { 'subject': 'math', 'score': 85 }, { 'subject': 'math', 'score': 72 }, { 'subject': 'math', 'score': 93 }, { 'subject': 'math', 'score': 68 }, { 'subject': 'science', 'score': 90 }, { 'subject': 'science', 'score': 78 }, { 'subject': 'science', 'score': 65 }, { 'subject': 'science', 'score': 88 } ]) accumulator_result = list(scores.aggregate([ { '$group': { '_id': '$subject', 'highestTwo': { '$maxN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N largest elements from an array field readings = db['readings'] readings.insert_many([ { '_id': 1, 'sensor': 'A', 'values': [45, 12, 78, 3, 56] }, { '_id': 2, 'sensor': 'B', 'values': [90, 23, 67, 11, 44] } ]) expression_result = list(readings.aggregate([ { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N largest values over a window in each partition stock_prices = db['stockPrices'] stock_prices.insert_many([ { '_id': 1, 'ticker': 'ABC', 'hour': 1, 'price': 50 }, { '_id': 2, 'ticker': 'ABC', 'hour': 2, 'price': 45 }, { '_id': 3, 'ticker': 'ABC', 'hour': 3, 'price': 60 }, { '_id': 4, 'ticker': 'ABC', 'hour': 4, 'price': 40 }, { '_id': 5, 'ticker': 'XYZ', 'hour': 1, 'price': 30 }, { '_id': 6, 'ticker': 'XYZ', 'hour': 2, 'price': 35 }, { '_id': 7, 'ticker': 'XYZ', 'hour': 3, 'price': 25 } ]) window_result = list(stock_prices.aggregate([ { '$setWindowFields': { 'partitionBy': '$ticker', 'sortBy': { 'hour': 1 }, 'output': { 'highestTwoSoFar': { '$maxN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()