本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$topN
8.0.1 版的新功能。
使用$group階段中的$topN累積器,根據指定的排序順序傳回群組中的前 N 個元素。如果群組包含少於 N 個元素,則 會$topN傳回群組中的所有元素。
參數
-
n:正整數或解析為一個的表達式,指定每個群組要傳回的最大結果數量。
-
sortBy:指定排序順序的文件。1 使用 遞增或 -1 遞減。
-
output:指定要從每個前 N 個文件傳回的欄位的表達式。
範例 (MongoDB Shell)
下列範例顯示如何使用$topN累積器來尋找銷售集合中每個項目的前 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", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
輸出
[
{ "_id": "xyz", "topTwoSales": [{ "quantity": 15, "price": 3 }, { "quantity": 9, "price": 6 }] },
{ "_id": "abc", "topTwoSales": [{ "quantity": 10, "price": 5 }, { "quantity": 7, "price": 8 }] }
]
視窗運算子用量範例 (MongoDB Shell)
8.0.2 版的新功能。
該$topN運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會output在每個視窗中的文件中傳回前 N 個文件 (根據運算子自己的 sortBy) 中的 陣列。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。
在 中用作視窗運算子時$setWindowFields, 限制$topN為 100 MB 的中繼資料。超過此限制的操作會傳回錯誤。
建立範例文件
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 }
]);
查詢範例
下列範例會依 分割文件player、依 排序每個分割區round,並傳回從分割區開頭到目前文件的兩個最高分回合。
db.matchScores.aggregate([
{
$setWindowFields: {
partitionBy: "$player",
sortBy: { round: 1 },
output: {
topTwoRoundsSoFar: {
$topN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
輸出
[
{ "_id": 1, "player": "Alice", "round": 1, "score": 20, "topTwoRoundsSoFar": [{ "round": 1, "score": 20 }] },
{ "_id": 2, "player": "Alice", "round": 2, "score": 35, "topTwoRoundsSoFar": [{ "round": 2, "score": 35 }, { "round": 1, "score": 20 }] },
{ "_id": 3, "player": "Alice", "round": 3, "score": 28, "topTwoRoundsSoFar": [{ "round": 2, "score": 35 }, { "round": 3, "score": 28 }] },
{ "_id": 4, "player": "Bob", "round": 1, "score": 15, "topTwoRoundsSoFar": [{ "round": 1, "score": 15 }] },
{ "_id": 5, "player": "Bob", "round": 2, "score": 40, "topTwoRoundsSoFar": [{ "round": 2, "score": 40 }, { "round": 1, "score": 15 }] }
]
每個文件都使用 擴增topTwoRoundsSoFar,其分割區中的兩個最高分的四捨五入,直到並包括目前的文件。如果視窗包含少於兩個文件,則會傳回所有文件。
程式碼範例
若要檢視使用 $topN 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group) 和視窗運算子用量 (在 中$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: top 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", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: top 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: {
topTwoRoundsSoFar: {
$topN: { 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: top 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', 'topTwoSales': { '$topN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } }
]))
pprint(accumulator_result)
# Window operator usage: top 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': {
'topTwoRoundsSoFar': {
'$topN': { '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()