本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$top
8.0.1 版的新功能。
使用$group階段中的$top累積器,根據指定的排序順序傳回每個群組的最高排名文件。
參數
範例 (MongoDB Shell)
下列範例顯示如何使用$top累積器來尋找銷售集合中每個項目的最高銷售 (最高數量)。
建立範例文件
db.sales.insertMany([
{ item: "abc", quantity: 10, price: 5 },
{ item: "abc", quantity: 5, price: 8 },
{ item: "xyz", quantity: 15, price: 3 },
{ item: "xyz", quantity: 7, price: 6 }
])
查詢範例
db.sales.aggregate([
{ $group: { _id: "$item", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
輸出
[
{ "_id": "xyz", "topSale": { "quantity": 15, "price": 3 } },
{ "_id": "abc", "topSale": { "quantity": 10, "price": 5 } }
]
程式碼範例
若要檢視使用 $top 運算子的程式碼範例,請選擇您要使用的語言標籤:
- 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", topSale: { $top: { 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', 'topSale': { '$top': { '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()