本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$min
$min 彙總運算子會傳回一組文件中指定欄位的最小值。此運算子有助於尋找一組文件中的最低值。
參數
範例 (MongoDB Shell)
下列範例示範 $min運算子的使用情況,以尋找跨多個文件之 age 欄位的最小值。
建立範例文件
db.users.insertMany([
{ name: "John", age: 35 },
{ name: "Jane", age: 28 },
{ name: "Bob", age: 42 },
{ name: "Alice", age: 31 }
]);
查詢範例
db.users.aggregate([
{ $group: { _id: null, minAge: { $min: "$age" } } },
{ $project: { _id: 0, minAge: 1 } }
])
輸出
[ { minAge: 28 } ]
視窗運算子用量範例 (MongoDB Shell)
8.0.2 版的新功能。
該$min運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會傳回每個視窗中文件的最小值。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。
在 中用作視窗運算子時$setWindowFields, 限制$min為 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: {
lowestSoFar: {
$min: "$price",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
輸出
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "lowestSoFar": 50 },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "lowestSoFar": 45 },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "lowestSoFar": 45 },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "lowestSoFar": 40 },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "lowestSoFar": 30 },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "lowestSoFar": 30 },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "lowestSoFar": 25 }
]
每個文件都會使用 擴增lowestSoFar,其分割區price內執行的最小值為 ,直到並包含目前的文件。
程式碼範例
若要檢視使用 $min 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group) 和視窗運算子用量 (在 中$setWindowFields):
- 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');
// Accumulator usage: minimum value across a group
const users = db.collection('users');
await users.insertMany([
{ name: "John", age: 35 },
{ name: "Jane", age: 28 },
{ name: "Bob", age: 42 },
{ name: "Alice", age: 31 }
]);
const accumulatorResult = await users.aggregate([
{ $group: { _id: null, minAge: { $min: "$age" } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: running minimum within 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: {
lowestSoFar: {
$min: "$price",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
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']
# Accumulator usage: minimum value across a group
users = db.users
users.insert_many([
{ "name": "John", "age": 35 },
{ "name": "Jane", "age": 28 },
{ "name": "Bob", "age": 42 },
{ "name": "Alice", "age": 31 }
])
accumulator_result = list(users.aggregate([
{ "$group": { "_id": None, "minAge": { "$min": "$age" } } }
]))
print('Accumulator result:', accumulator_result)
# Window operator usage: running minimum within 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": {
"lowestSoFar": {
"$min": "$price",
"window": { "documents": ["unbounded", "current"] }
}
}
}
}
]))
print('Window result:', window_result)
client.close()
example()