Explorer
MongoDB

Add a `total` field computed as `price * qty` to each `lineItems` document, then sort by `total` descending.

Problem Statement

<p>Add a <code>total</code> field computed as <code>price * qty</code> to each <code>lineItems</code> document, then sort by <code>total</code> descending.</p>

Examples

Input: lineItems collection: +-----+--------+-------+-----+ | _id | item | price | qty | +-----+--------+-------+-----+ | 1 | Widget | 10 | 5 | | 2 | Gadget | 50 | 1 | | 3 | Gizmo | 15 | 4 | +-----+--------+-------+-----+

Output: +-----+--------+-------+-----+-------+ | _id | item | price | qty | total | +-----+--------+-------+-----+-------+ | 3 | Gizmo | 15 | 4 | 60 | | 1 | Widget | 10 | 5 | 50 | | 2 | Gadget | 50 | 1 | 50 | +-----+--------+-------+-----+-------+

Explanation: The collection documents are sorted according to the specified field order.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Use db.<collection>.aggregate([ ... ]) to run a multi-stage data processing pipeline. šŸ’” Hint 2: Order pipeline stages logically (e.g. $match early to filter documents before processing). šŸ’” Hint 3: Convert the aggregation cursor using .toArray() at the end of the function.

Editorial & Approach

Problem Overview & Intuition

To solve "AddFields + Sort (Compute Then Rank)", we query the MongoDB document store. The goal is to add a `total` field computed as `price * qty` to each `lineitems` document, then 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.lineItems.aggregate([
    { $addFields: { total: { $multiply: ["$price", "$qty"] } } },
    { $sort: { total: -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.

AddFields + Sort (Compute Then Rank)

Medium

Add a total field computed as price * qty to each lineItems document, then sort by total descending.

Example Scenarios
1Example 1
Input:
lineItems collection
_iditempriceqty
1Widget105
2Gadget501
3Gizmo154
Output:
_iditempriceqtytotal
3Gizmo15460
1Widget10550
2Gadget50150
Explanation:

The collection documents are sorted according to the specified field order.

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

Run your MongoDB code to see results here.