本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$max
$max聚合运算符返回一组文档中指定字段的最大值。此运算符可用于查找一组文档中的最大值。
参数
示例(MongoDB Shell)
以下示例演示如何使用$max运算符在一组学生文档中查找最高分数。该$group阶段将所有文档组合在一起,$max运算符用于计算所有文档中该score字段的最大值。
创建示例文档
db.students.insertMany([
{ name: "John", score: 85 },
{ name: "Jane", score: 92 },
{ name: "Bob", score: 78 },
{ name: "Alice", score: 90 }
])
查询示例
db.students.aggregate([
{ $group: { _id: null, maxScore: { $max: "$score" } } },
{ $project: { _id: 0, maxScore: 1 } }
])
输出
[ { maxScore: 92 } ]
窗口运算符用法示例(MongoDB Shell)
8.0.2 版中的新内容。
该$max操作员还可以在$setWindowFields舞台中用作窗口操作员。在这种情况下,它返回每个窗口中文档的最大值。您可以在output字段下指定运算符,也可以选择使用window文档定义窗口边界。
在中用作窗口运算符时$setWindowFields,中间数据限制$max为 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: {
highestSoFar: {
$max: "$price",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
输出
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "highestSoFar": 50 },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "highestSoFar": 50 },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "highestSoFar": 60 },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "highestSoFar": 60 },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "highestSoFar": 30 },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "highestSoFar": 35 },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "highestSoFar": 35 }
]
每个文档都添加了highestSoFar,即其分区price内运行的最大值,直至包括当前文档。
代码示例
要查看使用$max运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示了累加器的用法(输入$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: maximum value across a group
const students = db.collection('students');
await students.insertMany([
{ name: "John", score: 85 },
{ name: "Jane", score: 92 },
{ name: "Bob", score: 78 },
{ name: "Alice", score: 90 }
]);
const accumulatorResult = await students.aggregate([
{ $group: { _id: null, maxScore: { $max: "$score" } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: running maximum 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: {
highestSoFar: {
$max: "$price",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
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')
db = client['test']
# Accumulator usage: maximum value across a group
students = db.students
students.insert_many([
{ "name": "John", "score": 85 },
{ "name": "Jane", "score": 92 },
{ "name": "Bob", "score": 78 },
{ "name": "Alice", "score": 90 }
])
accumulator_result = list(students.aggregate([
{ "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
]))
print('Accumulator result:', accumulator_result)
# Window operator usage: running maximum 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": {
"highestSoFar": {
"$max": "$price",
"window": { "documents": ["unbounded", "current"] }
}
}
}
}
]))
print('Window result:', window_result)
client.close()
example()