本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$bottomN
8.0.1 版的新功能。
使用$group階段中的$bottomN累積器,根據指定的排序順序傳回群組中的底部 N 元素。如果群組包含少於 N 個元素,則 會$bottomN傳回群組中的所有元素。
參數
-
n:正整數或解析為一個的表達式,指定每個群組要傳回的底部結果數量。
-
sortBy:指定排序順序的文件。1 使用 遞增或 -1 遞減。
-
output:指定要從每個底部 N 文件傳回的欄位的表達式。
範例 (MongoDB Shell)
下列範例顯示如何使用$bottomN累積器來尋找銷售集合中每個項目的最低 2 個銷售額 (最低數量)。
建立範例文件
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 }
])
查詢範例
db.sales.aggregate([
{ $group: { _id: "$item", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
輸出
[
{ "_id": "xyz", "bottomTwoSales": [{ "quantity": 9, "price": 6 }, { "quantity": 3, "price": 12 }] },
{ "_id": "abc", "bottomTwoSales": [{ "quantity": 7, "price": 8 }, { "quantity": 5, "price": 10 }] }
]
程式碼範例
若要檢視使用 $bottomN 運算子的程式碼範例,請選擇您要使用的語言標籤:
- 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", bottomTwoSales: { $bottomN: { 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', 'bottomTwoSales': { '$bottomN': { '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()