本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$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舞台中用作窗口操作员。在这种情况下,它返回每个窗口中前 N 个文档(根据操作员自己的sortBy)中的一个数组。output您可以在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()