Explorer
MongoDB

From the `transactions` collection, filter for `type: "purchase"`, group by `userId` to get total `amount` spent, and sort by total descending.

Problem Statement

<p>From the <code>transactions</code> collection, filter for <code>type: "purchase"</code>, group by <code>userId</code> to get total <code>amount</code> spent, and sort by total descending.</p>

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

šŸ’” 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 "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

  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.transactions.aggregate([
    { $match: { type: "purchase" } },
    { $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.

Match + Group + Sort

Medium

From the transactions collection, filter for type: "purchase", group by userId to get total amount spent, and sort by total descending.

Example Scenarios
1Example 1
Input:
transactions collection
_iduserIdtypeamount
1u1purchase50
2u2refund20
3u1purchase75
4u3purchase100
5u2purchase30
Output:
_idtotalSpent
u1125
u3100
u230
Explanation:

The aggregation pipeline processes the documents through stages to compute the grouped results.

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

Run your MongoDB code to see results here.