本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$minN
8.0.1 版的新功能。
Amazon DocumentDB 中的$minN運算子會傳回 N 個最小值。在$group階段中用作累積器時,它會傳回每個群組中 N 個最小值的陣列。用作陣列表達式運算子時,它會傳回陣列的 N 個最小元素。
參數
Behavior (行為)
陣列表達式運算子行為
-
您無法指定n小於 的值1。
-
$minN 會篩選掉input陣列中找到null的值。
-
如果指定的 n 大於或等於input陣列中的元素數目,則 會$minN傳回input陣列中的所有元素。
-
如果 input解析為非陣列值,則彙總操作錯誤。
-
如果 同時input包含數值和字串元素,則會根據 BSON 比較順序,在字串元素之前排序數值元素。
累積器行為
-
用作累積器時, n 必須是正整數表達式,其為常數或取決於 _id的值$group。
-
$minN 會篩選掉 null 值和遺失值。
-
如果群組包含的n元素少於 個,則 會$minN傳回群組中的所有元素。
-
$minN 會依照 BSON 比較順序比較輸入資料,以判斷適當的輸出類型。當輸入資料包含多個資料類型時,$minN輸出類型是比較順序中最低的。
輸出排序
$minN 不會以特定排序順序傳回值。如果需要保證特定排序順序,請$bottomN改用 ,或使用 包裝結果$sortArray。
範例 (MongoDB Shell)
下列範例顯示如何使用$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 Shell)
運算$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 Shell)
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,並傳回從分割區開頭到目前文件的兩個最低價格。
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,也就是其視窗內的兩個最小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()