Explorer
MongoDB

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

<p>You have <code>users</code> and <code>orders</code> collections. Find the total spending per user: for each order, group by <code>userId</code> and sum <code>amount</code>. Return sorted by total descending.</p>

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

šŸ’” Hint 1: This problem requires grouping documents by a key and aggregating values. Use db.<collection>.aggregate([...]) with a $group stage. šŸ’” Hint 2: In the $group stage, set _id to the grouping field (e.g. "$category" or "$dept") and use accumulator operators like $sum, $avg, $max, or $min. šŸ’” Hint 3: Remember to call .toArray() at the end of the aggregation pipeline to return the resolved documents array.

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

  1. Identify Target Collection: Access the collection through the db instance.
  2. Construct Query / Pipeline: Build the aggregation stages ($match, $group, $sort, etc.).
  3. 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

Time Complexity O(N) pipeline traversal through aggregation stages.
Space Complexity O(M) intermediate document buffer in aggregation pipeline.

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.

Multi-Collection Pattern: Cross-Reference

Hard

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.

Example Scenarios
1Example 1
Input:
orders collection
_iduserIdamount
1u1120
2u2300
3u180
4u350
5u2200
users collection
_idname
u1Alice
u2Bob
u3Charlie
Output:
_idtotalSpent
u2500
u1200
u350
Explanation:

The query retrieves all documents from the collection that satisfy the specified filter criteria.

MongoDB Editor
Loading Editor...
Query Results (JSON)

Run your MongoDB code to see results here.