From the `transactions` collection, filter for `type: "purchase"`, group by `userId` to get total `amount` spent, and sort by total descending.
Problem Statement
Examples
Input: transactions collection: +-----+--------+----------+--------+ | _id | userId | type | amount | +-----+--------+----------+--------+ | 1 | u1 | purchase | 50 | | 2 | u2 | refund | 20 | | 3 | u1 | purchase | 75 | | 4 | u3 | purchase | 100 | | 5 | u2 | purchase | 30 | +-----+--------+----------+--------+
Output: +-----+------------+ | _id | totalSpent | +-----+------------+ | u1 | 125 | | u3 | 100 | | u2 | 30 | +-----+------------+
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 "Match + Group + Sort", we query the MongoDB document store. The goal is to from the `transactions` collection, filter for `type: "purchase"`, group by `userid` to get total `amount` spent, and sort by total descending. 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.transactions.aggregate([
{ $match: { type: "purchase" } },
{ $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } }
]);
}
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.