View a markdown version of this page

$TopN - Amazon DocumentDB

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

$TopN

Baru dari versi 8.0.1.

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

Parameter

  • n: Bilangan bulat positif, atau ekspresi yang diselesaikan menjadi satu, menentukan berapa banyak hasil teratas 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 dokumen N teratas.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $topN akumulator untuk menemukan 2 penjualan teratas (jumlah tertinggi) 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", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])

Keluaran

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

Contoh kode

Untuk melihat contoh kode untuk menggunakan $topN operator, pilih tab untuk bahasa yang ingin Anda gunakan:

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'); const collection = db.collection('sales'); const result = await collection.aggregate([ { $group: { _id: "$item", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ]).toArray(); console.log(result); } 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'] collection = db['sales'] result = list(collection.aggregate([ { '$group': { '_id': '$item', 'topTwoSales': { '$topN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } } ])) pprint(result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()