View a markdown version of this page

$minN - Amazon DocumentDB

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

$minN

バージョン 8.0.1 から新規。

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

パラメータ

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

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

動作

配列式演算子の動作

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

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

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

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

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

アキュムレータの動作

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

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

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

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

出力順序

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

例 (MongoDB シェル)

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

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

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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]);

出力

[ { "_id": "math", "lowestTwo": [72, 68] }, { "_id": "science", "lowestTwo": [78, 65] } ]

式の使用例 (MongoDB シェル)

$minN 演算子を$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: { lowestThree: { $minN: { input: "$values", n: 3 } } }} ]);

出力

[ { "_id": 1, "lowestThree": [45, 12, 3] }, { "_id": 2, "lowestThree": [44, 23, 11] } ]

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

バージョン 8.0.2 の新機能。

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

注記

でウィンドウ演算子として使用する場合$setWindowFields、 $minNは 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: { lowestTwoSoFar: { $minN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

出力

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

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

コードの例

$minN 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。次の例は、アキュムレータの使用 ( の場合$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 smallest 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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N smallest 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: { lowestThree: { $minN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N smallest 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: { lowestTwoSoFar: { $minN: { 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 smallest 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', 'lowestTwo': { '$minN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N smallest 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': { 'lowestThree': { '$minN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N smallest 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': { 'lowestTwoSoFar': { '$minN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()