Add a `tier` field to orders: orders with total >= 500 get "premium", >= 100 get "standard", else "basic". Then count orders per tier.
Problem Statement
Examples
Input: orders collection: +-----+-------+ | _id | total | +-----+-------+ | 1 | 50 | | 2 | 150 | | 3 | 750 | | 4 | 200 | | 5 | 30 | | 6 | 500 | +-----+-------+
Output: +----------+-------+ | tier | count | +----------+-------+ | premium | 2 | | standard | 2 | | basic | 2 | +----------+-------+
Explanation: The collection documents are sorted according to the specified field order.
Complexity
Time Complexity: -
Space Complexity: -
Hints
Editorial & Approach
Problem Overview & Intuition
To solve "E-commerce: Order Value Distribution", we query the MongoDB document store. The goal is to add a `tier` field to orders: orders with total >= 500 get "premium", >= 100 get "standard", else "basic". then count orders per tier. Using a targeted find query, 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 query filter with appropriate comparison operators.
- Resolve Cursor: Invoke
.toArray()to transform the query cursor into the required array of documents.
Optimal Implementation (MongoDB)
function solve(db) {
const premium = db.orders.countDocuments({ total: { $gte: 500 } });
const standard = db.orders.find({ $and: [{ total: { $gte: 100 } }, { total: { $lt: 500 } }] }).toArray().length;
const basic = db.orders.countDocuments({ total: { $lt: 100 } });
return [{ tier: "premium", count: premium }, { tier: "standard", count: standard }, { tier: "basic", count: basic }];
}
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.