From `orders`, match orders with status `"completed"`, add a `discountedTotal` field (total * 0.9), sort by discountedTotal desc, and limit to 2.
Problem Statement
Examples
Input: orders collection: +-----+----------+-------+-----------+ | _id | customer | total | status | +-----+----------+-------+-----------+ | 1 | A | 500 | completed | | 2 | B | 200 | pending | | 3 | C | 800 | completed | | 4 | D | 300 | completed | +-----+----------+-------+-----------+
Output: +-----+----------+-------+-----------+-----------------+ | _id | customer | total | status | discountedTotal | +-----+----------+-------+-----------+-----------------+ | 3 | C | 800 | completed | 720 | | 1 | A | 500 | completed | 450 | +-----+----------+-------+-----------+-----------------+
Explanation: The aggregation pipeline processes the documents through stages to compute the grouped results.
Complexity
Time Complexity: -
Space Complexity: -
Hints
Editorial & Approach
Problem Overview & Intuition
To solve "Pipeline: Match + AddFields + Sort + Limit", we query the MongoDB document store. The goal is to from `orders`, match orders with status `"completed"`, add a `discountedtotal` field (total * 0.9), sort by discountedtotal desc, and limit to 2. Using an aggregation pipeline, the database engine filters and structures the BSON documents efficiently.
Step-by-Step Approach
- Identify Target Collection: Access the collection through the
dbinstance. - Construct Query / Pipeline: Build the aggregation stages ($match, $group, $sort, etc.).
- Resolve Cursor: Invoke
.toArray()to transform the query cursor into the required array of documents.
Optimal Implementation (MongoDB)
function solve(db) {
return db.orders.aggregate([
{ $match: { status: "completed" } },
{ $addFields: { discountedTotal: { $multiply: ["$total", 0.9] } } },
{ $sort: { discountedTotal: -1 } },
{ $limit: 2 }
]);
}
Complexity Analysis
Key Considerations & Edge Cases
- Empty Collections: If no documents match, the query cleanly returns an empty array
[]. - Missing / NULL Fields: Missing fields in documents are handled safely without throwing runtime exceptions.
- Type Coercion: BSON types (ObjectId, Numbers, Strings) are compared strictly according to MongoDB specifications.