Explorer
MongoDB

Project only the `name` and `price` fields (exclude `_id`) from the `menu` collection.

Problem Statement

<p>Project only the <code>name</code> and <code>price</code> fields (exclude <code>_id</code>) from the <code>menu</code> collection.</p>

Examples

Input: menu collection: +-----+--------+-------+----------+ | _id | name | price | calories | +-----+--------+-------+----------+ | 1 | Burger | 10 | 500 | | 2 | Salad | 8 | 200 | | 3 | Fries | 5 | 400 | +-----+--------+-------+----------+

Output: +--------+-------+ | name | price | +--------+-------+ | Burger | 10 | | Salad | 8 | | Fries | 5 | +--------+-------+

Explanation: The query projects only the requested document fields matching the criteria.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Use the $project stage in an aggregation pipeline to include, exclude, or compute new document fields. šŸ’” Hint 2: Set fields to 1 (include) or 0 (exclude), and use expression operators to reshape data. šŸ’” Hint 3: Finalize the pipeline and execute with .toArray() to return the structured document array.

Editorial & Approach

Problem Overview & Intuition

To solve "Aggregation: $project Stage", we query the MongoDB document store. The goal is to project only the `name` and `price` fields (exclude `_id`) from the `menu` collection. 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.menu.aggregate([{ $project: { _id: 0, name: 1, price: 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.

Aggregation: $project Stage

Medium

Project only the name and price fields (exclude _id) from the menu collection.

Example Scenarios
1Example 1
Input:
menu collection
_idnamepricecalories
1Burger10500
2Salad8200
3Fries5400
Output:
nameprice
Burger10
Salad8
Fries5
Explanation:

The query projects only the requested document fields matching the criteria.

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

Run your MongoDB code to see results here.