View a markdown version of this page

$max - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$max

Operator $max agregasi mengembalikan nilai maksimum bidang tertentu di seluruh kumpulan dokumen. Operator ini berguna untuk menemukan nilai tertinggi dalam satu set dokumen.

Parameter

  • expression: Ekspresi yang digunakan untuk menghitung nilai maksimum.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $max operator untuk menemukan skor maksimum dalam kumpulan dokumen siswa. T $group ahap mengelompokkan semua dokumen bersama-sama, dan $max operator digunakan untuk menghitung nilai maksimum score bidang di semua dokumen.

Buat dokumen sampel

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

Contoh kueri

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

Keluaran

[ { maxScore: 92 } ]

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$maxOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan nilai maksimum untuk dokumen di setiap jendela. Anda menentukan operator di bawah output bidang, dan secara opsional menentukan batas jendela dengan window dokumen.

catatan

Ketika digunakan sebagai operator jendela di$setWindowFields, $max dibatasi hingga 100 MB data perantara. Operasi yang melebihi batas ini mengembalikan kesalahan.

Buat dokumen sampel

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

Contoh kueri

Contoh berikut mempartisi dokumen berdasarkanticker, mengurutkan setiap partisi berdasarkanhour, dan mengembalikan harga tertinggi yang terlihat dari awal partisi melalui dokumen saat ini.

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

Keluaran

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

Setiap dokumen ditambah denganhighestSoFar, maksimum berjalan di price dalam partisinya hingga dan termasuk dokumen saat ini.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $max operator, pilih tab untuk bahasa yang ingin Anda gunakan. Contoh berikut menunjukkan penggunaan akumulator (in$group) dan penggunaan operator jendela (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()