Lesson 20 of 50 – Projection in MongoDB
40%

Projection in MongoDB

Projection in MongoDB allows us to select which fields should appear in query results. Instead of displaying every field in a document, we can return only the information we need.

For example, a student document may contain a name, age, mobile number, address, course, and fee. If we only need the student's name and course, projection can return those fields without displaying the others.

1. What Is Projection?

Projection determines which fields are included or excluded in the documents returned by a query.

Example Document
{
    _id: 1,
    name: "Rahul",
    age: 20,
    course: "Java",
    fee: 5000,
    city: "Patna"
}

To display the complete document, use:

db.students.find()

To display only the student's name and course, use projection.

2. Basic Projection Syntax

Syntax
db.collection.find(
    { filter },
    { field: 1 }
)

The second argument of find() specifies the projection.

  • 1 means include a field.
  • 0 means exclude a field.
Example
db.students.find(
    {},
    { name: 1, course: 1 }
)

This returns the name and course fields. The _id field is included by default.

Example result:

{
    _id: 1,
    name: "Rahul",
    course: "Java"
}

3. Include Specific Fields

Use 1 to include the fields you want to display.

Example 1: Display Name Only
db.students.find(
    {},
    { name: 1 }
)
Example 2: Display Name and Age
db.students.find(
    {},
    { name: 1, age: 1 }
)
Example 3: Display Name, Course, and Fee
db.students.find(
    {},
    {
        name: 1,
        course: 1,
        fee: 1
    }
)

Only the selected fields and the default _id field are returned.

4. Exclude Specific Fields

Use 0 to exclude a field from the returned documents.

Example 1: Hide the Age Field
db.students.find(
    {},
    { age: 0 }
)

All fields are returned except age.

Example 2: Hide Mobile Number
db.students.find(
    {},
    { mobile: 0 }
)
Example 3: Hide Address and Fee
db.students.find(
    {},
    {
        address: 0,
        fee: 0
    }
)

This returns the other fields while excluding the specified fields.

5. Exclude the _id Field

MongoDB includes the _id field by default, even when we include other fields. To hide it, explicitly set _id: 0.

Example
db.students.find(
    {},
    {
        _id: 0,
        name: 1,
        course: 1
    }
)

Example result:

{
    name: "Rahul",
    course: "Java"
}

The result contains only the name and course fields.

6. Projection with a Filter

We can combine a filter with projection. The filter selects matching documents, while projection controls which fields are returned.

Example: Find Java Students
db.students.find(
    { course: "Java" },
    {
        _id: 0,
        name: 1,
        age: 1
    }
)

This selects students enrolled in Java and displays only their names and ages.

Example: Find Students with Fees Above 5000
db.students.find(
    { fee: { $gt: 5000 } },
    {
        _id: 0,
        name: 1,
        fee: 1
    }
)

This returns the name and fee of students whose fees are greater than 5000.

7. Projection with sort() and limit()

Projection can be combined with sorting and limiting to return a specific number of records with selected fields.

Example: Three Highest-Paid Employees
db.employees.find(
    {},
    {
        _id: 0,
        name: 1,
        salary: 1
    }
)
.sort({ salary: -1 })
.limit(3)

This returns up to three employees with the highest salaries, displaying only their names and salaries.

Example: Five Cheapest Products
db.products.find(
    {},
    {
        _id: 0,
        product_name: 1,
        price: 1
    }
)
.sort({ price: 1 })
.limit(5)

This returns up to five products with the lowest prices and displays only the product name and price.

8. Projection with Embedded Documents

MongoDB supports embedded documents. We can use dot notation to include a particular nested field.

Example Document
{
    name: "Rahul",
    course: "Java",
    address: {
        city: "Patna",
        state: "Bihar",
        pincode: 800001
    }
}
Display Only the City
db.students.find(
    {},
    {
        _id: 0,
        name: 1,
        "address.city": 1
    }
)

This returns the student's name and the city field from the embedded address document.

9. Important Projection Rules

  • 1 includes a field.
  • 0 excludes a field.
  • The _id field is included by default.
  • You can exclude _id while including other fields.
  • In a normal projection, do not mix inclusion and exclusion for ordinary fields.
  • The special _id field can be excluded from an inclusion projection.
  • Projection changes the returned result, not the stored document.
Remember: This is valid: { _id: 0, name: 1, age: 1 }. But this ordinary inclusion/exclusion mix is invalid: { name: 1, age: 0 }.

10. Practical Assignment

Create a collection named practice_projection and insert these sample documents:

db.practice_projection.insertMany([
    {
        _id: 1,
        name: "Rahul",
        age: 22,
        course: "Java",
        fee: 5000,
        city: "Patna"
    },
    {
        _id: 2,
        name: "Priya",
        age: 19,
        course: "Python",
        fee: 6000,
        city: "Gaya"
    },
    {
        _id: 3,
        name: "Aman",
        age: 21,
        course: "Java",
        fee: 4500,
        city: "Aurangabad"
    },
    {
        _id: 4,
        name: "Neha",
        age: 20,
        course: "HTML",
        fee: 7000,
        city: "Patna"
    }
])
Complete these tasks:
  1. Display only the name field.
  2. Display name and age, excluding the _id field.
  3. Display all fields except the fee field.
  4. Find Java students and display only their names.
  5. Display name, course, and fee for every student.
  6. Find students whose fee is greater than 5000 and display their names and fees.
  7. Display the two highest-paid students with only their names and fees.
  8. Explain the difference between including and excluding fields in projection.

Run the insertion command only once, or clear the test collection before inserting the same sample data again.

🧠 Quick Quiz

1. What does 1 mean in a projection?




2. Which field is included by default in MongoDB query results?




3. Which projection displays name and age without _id?