View a markdown version of this page

$max - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$max

L'operatore $max di aggregazione restituisce il valore massimo di un campo specificato in un set di documenti. Questo operatore è utile per trovare il valore più alto in un set di documenti.

Parametri

  • expression: L'espressione da utilizzare per calcolare il valore massimo.

Esempio (MongoDB Shell)

L'esempio seguente dimostra come utilizzare l'$maxoperatore per trovare il punteggio massimo in una raccolta di documenti degli studenti. La $group fase raggruppa tutti i documenti e l'$maxoperatore viene utilizzato per calcolare il valore massimo del score campo in tutti i documenti.

Crea documenti di esempio

db.students.insertMany([ { name: "John", score: 85 }, { name: "Jane", score: 92 }, { name: "Bob", score: 78 }, { name: "Alice", score: 90 } ])

Esempio di interrogazione

db.students.aggregate([ { $group: { _id: null, maxScore: { $max: "$score" } } }, { $project: { _id: 0, maxScore: 1 } } ])

Output

[ { maxScore: 92 } ]

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$maxoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce il valore massimo per i documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Nota

Se utilizzato come operatore di finestra in$setWindowFields, $max è limitato a 100 MB di dati intermedi. Un'operazione che supera questo limite restituisce un errore.

Crea documenti di esempio

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 } ]);

Esempio di interrogazione

L'esempio seguente suddivide i documenti in baseticker, ordina ogni partizione in base hour e restituisce il prezzo più alto visto dall'inizio della partizione fino al documento corrente.

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestSoFar: { $max: "$price", window: { documents: ["unbounded", "current"] } } } } } ]);

Output

[ { "_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 } ]

Ogni documento viene ampliato con un numero massimo di caratteri price all'interno della partizione corrispondentehighestSoFar, fino al documento corrente incluso.

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo $max dell'operatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (in$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()