View a markdown version of this page

$max - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$max

$max 彙總運算子會傳回一組文件中指定欄位的最大值。此運算子適用於尋找一組文件中的最高值。

參數

  • expression:用來計算最大值的表達式。

範例 (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()