本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$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 } ]
程式碼範例
若要檢視使用 $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()