From `apiLogs`, group by `tenantId` to get total `callsCount`, sort descending, and return the top 2 consumers.
Problem Statement
Examples
Input: apiLogs collection: +-----+----------+------------+ | _id | tenantId | callsCount | +-----+----------+------------+ | 1 | t1 | 1500 | | 2 | t2 | 3000 | | 3 | t1 | 2200 | | 4 | t3 | 500 | +-----+----------+------------+
Output: +-----+------------+ | _id | totalCalls | +-----+------------+ | t1 | 3700 | | t2 | 3000 | +-----+------------+
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 "Top API Consumers (Group + Sort + Limit)", we query the MongoDB document store. The goal is to from `apilogs`, group by `tenantid` to get total `callscount`, sort descending, and return the top 2 consumers. 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.apiLogs.aggregate([
{ $group: { _id: "$tenantId", totalCalls: { $sum: "$callsCount" } } },
{ $sort: { totalCalls: -1 } },
{ $limit: 2 }
]);
}
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.