You have `users` and `orders` collections. Find the total spending per user: for each order, group by `userId` and sum `amount`. Return sorted by total descending.
Problem Statement
Examples
Input: orders collection: +-----+--------+--------+ | _id | userId | amount | +-----+--------+--------+ | 1 | u1 | 120 | | 2 | u2 | 300 | | 3 | u1 | 80 | | 4 | u3 | 50 | | 5 | u2 | 200 | +-----+--------+--------+ users collection: +-----+---------+ | _id | name | +-----+---------+ | u1 | Alice | | u2 | Bob | | u3 | Charlie | +-----+---------+
Output: +-----+------------+ | _id | totalSpent | +-----+------------+ | u2 | 500 | | u1 | 200 | | u3 | 50 | +-----+------------+
Explanation: The query retrieves all documents from the collection that satisfy the specified filter criteria.
Complexity
Time Complexity: -
Space Complexity: -
Hints
Editorial & Approach
Problem Overview & Intuition
To solve "Multi-Collection Pattern: Cross-Reference", we query the MongoDB document store. The goal is to you have `users` and `orders` collections. find the total spending per user: for each order, group by `userid` and sum `amount`. return sorted 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.orders.aggregate([
{ $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.