View a markdown version of this page

$min - Amazon DocumentDB

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

$min

Baru dari versi 8.0.1.

$minNOperator di Amazon DocumentDB mengembalikan N nilai terkecil. Ketika digunakan sebagai akumulator dalam $group tahap, ia mengembalikan array dari N nilai minimum di setiap grup. Ketika digunakan sebagai operator ekspresi array, ia mengembalikan N elemen minimum dari array.

Parameter

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

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

Perilaku

Perilaku operator ekspresi array

  • Anda tidak dapat menentukan nilai n kurang dari1.

  • $minNmenyaring null nilai yang ditemukan dalam input array.

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

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

  • Jika input berisi elemen numerik dan string, elemen numerik diurutkan sebelum elemen string 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.

  • $minNmenyaring nilai nol dan hilang.

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

  • $minNmembandingkan data input mengikuti urutan perbandingan BSON untuk menentukan jenis keluaran yang sesuai. Ketika data input berisi beberapa tipe data, tipe $minN output adalah yang terendah dalam urutan perbandingan.

Pemesanan keluaran

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

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $minN akumulator untuk mengambil dua skor terendah 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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]);

Keluaran

[ { "_id": "math", "lowestTwo": [72, 68] }, { "_id": "science", "lowestTwo": [78, 65] } ]

Contoh penggunaan ekspresi (MongoDB Shell)

$minNOperator juga dapat digunakan sebagai ekspresi dalam $project tahap untuk mengembalikan N elemen terkecil 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: { lowestThree: { $minN: { input: "$values", n: 3 } } }} ]);

Keluaran

[ { "_id": 1, "lowestThree": [45, 12, 3] }, { "_id": 2, "lowestThree": [44, 23, 11] } ]

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$minNOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan array hingga nilai ter n kecil 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, $minN 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 terendah yang terlihat dari awal partisi melalui dokumen saat ini.

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

Keluaran

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

Setiap dokumen ditambah denganlowestTwoSoFar, dua price nilai terkecil 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 $minN 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 smallest 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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N smallest 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: { lowestThree: { $minN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N smallest 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: { lowestTwoSoFar: { $minN: { 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 smallest 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', 'lowestTwo': { '$minN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N smallest 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': { 'lowestThree': { '$minN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N smallest 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': { 'lowestTwoSoFar': { '$minN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()