$topN
New from version 8.0.1.
Use the $topN accumulator in the $group stage to return the top N elements within a group according to a specified sort order. If a group contains fewer than N elements, $topN returns all elements in the group.
Parameters
-
n: A positive integer, or an expression that resolves to one, specifying how many top results to return per group. -
sortBy: A document specifying the sort order. Use1for ascending or-1for descending. -
output: An expression that specifies the fields to return from each of the top N documents.
Example (MongoDB Shell)
The following example demonstrates how to use the $topN accumulator to find the top 2 sales (highest quantity) per item in a sales collection.
Create sample documents
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 } ])
Query example
db.sales.aggregate([ { $group: { _id: "$item", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } } ])
Output
[
{ "_id": "xyz", "topTwoSales": [{ "quantity": 15, "price": 3 }, { "quantity": 9, "price": 6 }] },
{ "_id": "abc", "topTwoSales": [{ "quantity": 10, "price": 5 }, { "quantity": 7, "price": 8 }] }
]
Code examples
To view a code example for using the $topN operator, choose the tab for the language that you want to use: