View a markdown version of this page

$BottomN - Amazon DocumentDB

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

$BottomN

Baru dari versi 8.0.1.

Gunakan $bottomN akumulator di $group tahap untuk mengembalikan N elemen bawah dalam grup sesuai dengan urutan pengurutan yang ditentukan. Jika grup berisi kurang dari N elemen, $bottomN mengembalikan semua elemen dalam grup.

Parameter

  • n: Bilangan bulat positif, atau ekspresi yang diselesaikan menjadi satu, menentukan berapa banyak hasil bawah yang akan dikembalikan per grup.

  • sortBy: Dokumen yang menentukan urutan pengurutan. Gunakan 1 untuk naik atau -1 turun.

  • output: Ekspresi yang menentukan bidang yang akan dikembalikan dari masing-masing N dokumen bawah.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $bottomN akumulator untuk menemukan 2 penjualan terbawah (jumlah terendah) per item dalam koleksi penjualan.

Buat dokumen sampel

db.sales.insertMany([ { item: "abc", quantity: 10, price: 5 }, { item: "abc", quantity: 7, price: 8 }, { item: "abc", quantity: 5, price: 10 }, { item: "xyz", quantity: 15, price: 3 }, { item: "xyz", quantity: 9, price: 6 }, { item: "xyz", quantity: 3, price: 12 } ])

Contoh kueri

db.sales.aggregate([ { $group: { _id: "$item", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

Keluaran

[ { "_id": "xyz", "bottomTwoSales": [{ "quantity": 9, "price": 6 }, { "quantity": 3, "price": 12 }] }, { "_id": "abc", "bottomTwoSales": [{ "quantity": 7, "price": 8 }, { "quantity": 5, "price": 10 }] } ]

Contoh penggunaan operator jendela (MongoDB Shell)

Baru dari versi 8.0.2.

$bottomNOperator juga dapat digunakan sebagai operator jendela di pang $setWindowFields gung. Dalam konteks ini, ia mengembalikan array output dari dokumen N bawah (sesuai dengan operator sendirisortBy) di antara 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, $bottomN dibatasi hingga 100 MB data perantara. Operasi yang melebihi batas ini mengembalikan kesalahan.

Buat dokumen sampel

db.matchScores.insertMany([ { _id: 1, player: "Alice", round: 1, score: 20 }, { _id: 2, player: "Alice", round: 2, score: 35 }, { _id: 3, player: "Alice", round: 3, score: 28 }, { _id: 4, player: "Bob", round: 1, score: 15 }, { _id: 5, player: "Bob", round: 2, score: 40 } ]);

Contoh kueri

Contoh berikut mempartisi dokumen berdasarkanplayer, mengurutkan setiap partisi berdasarkanround, dan mengembalikan dua putaran skor terendah yang terlihat dari awal partisi melalui dokumen saat ini.

db.matchScores.aggregate([ { $setWindowFields: { partitionBy: "$player", sortBy: { round: 1 }, output: { bottomTwoRoundsSoFar: { $bottomN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } }, window: { documents: ["unbounded", "current"] } } } } } ]);

Keluaran

[ { "_id": 1, "player": "Alice", "round": 1, "score": 20, "bottomTwoRoundsSoFar": [{ "round": 1, "score": 20 }] }, { "_id": 2, "player": "Alice", "round": 2, "score": 35, "bottomTwoRoundsSoFar": [{ "round": 2, "score": 35 }, { "round": 1, "score": 20 }] }, { "_id": 3, "player": "Alice", "round": 3, "score": 28, "bottomTwoRoundsSoFar": [{ "round": 3, "score": 28 }, { "round": 1, "score": 20 }] }, { "_id": 4, "player": "Bob", "round": 1, "score": 15, "bottomTwoRoundsSoFar": [{ "round": 1, "score": 15 }] }, { "_id": 5, "player": "Bob", "round": 2, "score": 40, "bottomTwoRoundsSoFar": [{ "round": 2, "score": 40 }, { "round": 1, "score": 15 }] } ]

Setiap dokumen ditambah denganbottomTwoRoundsSoFar, dua putaran skor terendah dalam partisinya hingga dan termasuk dokumen saat ini. Jika jendela berisi kurang dari dua dokumen, semuanya dikembalikan.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $bottomN 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 uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); // Accumulator usage: bottom N documents per group const sales = db.collection('sales'); await sales.insertMany([ { item: "abc", quantity: 10, price: 5 }, { item: "abc", quantity: 7, price: 8 }, { item: "abc", quantity: 5, price: 10 }, { item: "xyz", quantity: 15, price: 3 }, { item: "xyz", quantity: 9, price: 6 }, { item: "xyz", quantity: 3, price: 12 } ]); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$item", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: bottom two rounds so far within each partition const matchScores = db.collection('matchScores'); await matchScores.insertMany([ { _id: 1, player: "Alice", round: 1, score: 20 }, { _id: 2, player: "Alice", round: 2, score: 35 }, { _id: 3, player: "Alice", round: 3, score: 28 }, { _id: 4, player: "Bob", round: 1, score: 15 }, { _id: 5, player: "Bob", round: 2, score: 40 } ]); const windowResult = await matchScores.aggregate([ { $setWindowFields: { partitionBy: "$player", sortBy: { round: 1 }, output: { bottomTwoRoundsSoFar: { $bottomN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): client = None try: 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: bottom N documents per group sales = db['sales'] sales.insert_many([ { 'item': 'abc', 'quantity': 10, 'price': 5 }, { 'item': 'abc', 'quantity': 7, 'price': 8 }, { 'item': 'abc', 'quantity': 5, 'price': 10 }, { 'item': 'xyz', 'quantity': 15, 'price': 3 }, { 'item': 'xyz', 'quantity': 9, 'price': 6 }, { 'item': 'xyz', 'quantity': 3, 'price': 12 } ]) accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$item', 'bottomTwoSales': { '$bottomN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(accumulator_result) # Window operator usage: bottom two rounds so far within each partition match_scores = db['matchScores'] match_scores.insert_many([ { '_id': 1, 'player': 'Alice', 'round': 1, 'score': 20 }, { '_id': 2, 'player': 'Alice', 'round': 2, 'score': 35 }, { '_id': 3, 'player': 'Alice', 'round': 3, 'score': 28 }, { '_id': 4, 'player': 'Bob', 'round': 1, 'score': 15 }, { '_id': 5, 'player': 'Bob', 'round': 2, 'score': 40 } ]) window_result = list(match_scores.aggregate([ { '$setWindowFields': { 'partitionBy': '$player', 'sortBy': { 'round': 1 }, 'output': { 'bottomTwoRoundsSoFar': { '$bottomN': { 'n': 2, 'sortBy': { 'score': -1 }, 'output': { 'round': '$round', 'score': '$score' } }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) pprint(window_result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()