本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$max
$max聚合阶段用于返回管道阶段中所有文档中指定字段的最大值。此运算符对于查找一组文档中的最大值很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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 } ]
代码示例
要查看使用该$max命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findMaxScore() {
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');
const students = db.collection('students');
const result = await students.aggregate([
{ $group: { _id: null, maxScore: { $max: "$score" } } }
]).toArray();
console.log(result);
await client.close();
}
findMaxScore();
- Python
-
from pymongo import MongoClient
def find_max_score():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
students = db.students
result = list(students.aggregate([
{ "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
]))
print(result)
client.close()
find_max_score()