View a markdown version of this page

$Maks - Amazon DocumentDB

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

$Maks

Baru dari versi 8.0.1.

$maxNOperator di Amazon DocumentDB mengembalikan N nilai terbesar. Ketika digunakan sebagai akumulator dalam $group tahap, ia mengembalikan array dari N nilai maksimum di setiap grup. Ketika digunakan sebagai operator ekspresi array, ia mengembalikan N elemen maksimum dari sebuah array.

Parameter

  • input: Ekspresi yang menyelesaikan ke array atau bidang dari mana untuk mengembalikan n nilai maksimum.

  • n: Ekspresi yang diselesaikan ke bilangan bulat positif yang menentukan berapa banyak nilai maksimum yang akan dikembalikan.

Perilaku

Perilaku operator ekspresi array

  • Anda tidak dapat menentukan nilai n kurang dari1.

  • $maxNmenyaring null nilai yang ditemukan dalam input array.

  • Jika yang n ditentukan lebih besar dari atau sama dengan jumlah elemen dalam input array, $maxN mengembalikan semua elemen dalam input array.

  • Jika input diselesaikan ke nilai non-array, kesalahan operasi agregasi.

  • Jika input berisi elemen numerik dan string, elemen string diurutkan sebelum elemen numerik sesuai dengan urutan perbandingan BSON.

Perilaku akumulator

  • Ketika digunakan sebagai akumulator, n harus berupa ekspresi integral positif yang merupakan konstanta atau tergantung pada _id nilai untuk$group.

  • $maxNmenyaring nilai nol dan hilang.

  • Jika grup berisi lebih sedikit dari n elemen, $maxN mengembalikan semua elemen dalam grup.

  • $maxNmembandingkan data input mengikuti urutan perbandingan BSON untuk menentukan jenis keluaran yang sesuai. Ketika data input berisi beberapa tipe data, jenis $maxN keluaran adalah yang tertinggi dalam urutan perbandingan.

Pemesanan keluaran

$maxNmengembalikan nilai tanpa urutan tertentu. Jika menjamin urutan pengurutan tertentu adalah persyaratan, gunakan sebagai $topN gantinya, atau bungkus hasilnya dengan$sortArray.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $maxN akumulator untuk mengambil dua skor tertinggi untuk setiap subjek.

Buat dokumen sampel

db.scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]);

Contoh kueri

db.scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]);

Keluaran

[ { "_id": "math", "highestTwo": [85, 93] }, { "_id": "science", "highestTwo": [88, 90] } ]

Contoh penggunaan ekspresi (MongoDB Shell)

$maxNOperator juga dapat digunakan sebagai ekspresi dalam $project tahap untuk mengembalikan N elemen terbesar dari bidang array.

Buat dokumen sampel

db.readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]);

Contoh kueri

db.readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } }} ]);

Keluaran

[ { "_id": 1, "highestThree": [45, 56, 78] }, { "_id": 2, "highestThree": [44, 90, 67] } ]

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$maxNOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan array hingga nilai n terbesar 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, $maxN 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 dua harga tertinggi yang terlihat dari awal partisi melalui dokumen saat ini.

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

Keluaran

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "highestTwoSoFar": [50] }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "highestTwoSoFar": [50, 45] }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "highestTwoSoFar": [60, 50] }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "highestTwoSoFar": [60, 50] }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "highestTwoSoFar": [30] }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "highestTwoSoFar": [35, 30] }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "highestTwoSoFar": [35, 30] } ]

Setiap dokumen ditambah denganhighestTwoSoFar, dua price nilai terbesar di dalam jendelanya. Seperti disebutkan di bagian Output Order, urutan nilai dalam array yang dikembalikan tidak dijamin.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $maxN operator, pilih tab untuk bahasa yang ingin Anda gunakan. Contoh berikut menunjukkan penggunaan akumulator (in$group), penggunaan ekspresi (in$project), dan penggunaan operator jendela (in$setWindowFields):

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); // Accumulator usage: N largest values per group const scores = db.collection('scores'); await scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]); const accumulatorResult = await scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N largest elements from an array field const readings = db.collection('readings'); await readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]); const expressionResult = await readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N largest values over a window in 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: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } finally { 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') try: db = client['test'] # Accumulator usage: N largest values per group scores = db['scores'] scores.insert_many([ { 'subject': 'math', 'score': 85 }, { 'subject': 'math', 'score': 72 }, { 'subject': 'math', 'score': 93 }, { 'subject': 'math', 'score': 68 }, { 'subject': 'science', 'score': 90 }, { 'subject': 'science', 'score': 78 }, { 'subject': 'science', 'score': 65 }, { 'subject': 'science', 'score': 88 } ]) accumulator_result = list(scores.aggregate([ { '$group': { '_id': '$subject', 'highestTwo': { '$maxN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N largest elements from an array field readings = db['readings'] readings.insert_many([ { '_id': 1, 'sensor': 'A', 'values': [45, 12, 78, 3, 56] }, { '_id': 2, 'sensor': 'B', 'values': [90, 23, 67, 11, 44] } ]) expression_result = list(readings.aggregate([ { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N largest values over a window in 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': { 'highestTwoSoFar': { '$maxN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()