本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$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()