View a markdown version of this page

$maxN - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$maxN

8.0.1 版的新功能。

Amazon DocumentDB 中的$maxN運算子會傳回 N 個最大值。在$group階段中用作累積器時,它會傳回每個群組中 N 個最大值的陣列。用作陣列表達式運算子時,它會傳回陣列的 N 個元素上限。

參數

  • input:解析為要傳回n最大值的陣列或欄位的表達式。

  • n:解析為正整數的表達式,指定要傳回多少最大值。

Behavior (行為)

陣列表達式運算子行為

  • 您無法指定n小於 的值1

  • $maxN 會篩選掉input陣列中找到null的值。

  • 如果指定的 n 大於或等於input陣列中的元素數目,則 會$maxN傳回input陣列中的所有元素。

  • 如果 input解析為非陣列值,則彙總操作錯誤。

  • 如果 同時input包含數值和字串元素,則字串元素會根據 BSON 比較順序在數值元素之前排序。

累積器行為

  • 用作累積器時, n 必須是正整數表達式,其為常數或取決於 _id的值$group

  • $maxN 會篩選掉 null 值和遺失值。

  • 如果群組包含的n元素少於 個,則 會$maxN傳回群組中的所有元素。

  • $maxN 會依照 BSON 比較順序比較輸入資料,以判斷適當的輸出類型。當輸入資料包含多個資料類型時,$maxN輸出類型在比較順序中最高。

輸出排序

$maxN 不會以特定排序順序傳回值。如果需要保證特定排序順序,請$topN改用 ,或使用 包裝結果$sortArray

範例 (MongoDB Shell)

下列範例顯示如何使用$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 Shell)

運算$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] } ]

程式碼範例

若要檢視使用 $maxN 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group) 和表達式用量 (在 中$project):

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'); 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'); const expressionResult = await readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); } 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'] 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'] expression_result = list(readings.aggregate([ { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) finally: client.close() example()