$documentNumber
Assigns sequential document numbers to each document within a partition based on specified sort order, providing positional ranking.
Syntax
{ $documentNumber: {} }
Examples
Retrieve document number by total sales
Assign sequential numbers to stores sorted by sales within company
Query:
db.stores.aggregate([{ $match: { "company": { $in: ["First Up Consultants"] } } }, { $setWindowFields: { "partitionBy": "$company", "sortBy": { "sales.totalSales": -1 }, "output": { "documentNumber": { "$documentNumber": {} } } } }, { $project: { "company": 1, "documentNumber": 1 } }])
Output:
Stores with sequential document numbers based on sales ranking
Number products by price
Assign document numbers to products sorted by price within categories
Query:
db.products.aggregate([{ $setWindowFields: { "partitionBy": "$category", "sortBy": { "price": 1 }, "output": { "pricePosition": { "$documentNumber": {} } } } }])
Output:
Products with sequential position numbers based on price ordering