Project MongoDB Fields

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to use MongoDB projection to select and exclude specific fields when querying documents. Projection allows you to control which fields are returned in your query results, enabling you to reduce unnecessary data transfer and improve query performance. You will start by selecting include fields, then move on to specifying exclude fields, mixing include and exclude, projecting nested fields, and formatting output fields. By the end of this lab, you will have a solid understanding of how to effectively utilize projection in your MongoDB queries.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/ArrayandEmbeddedDocumentsGroup(["`Array and Embedded Documents`"]) mongodb(("`MongoDB`")) -.-> mongodb/AggregationOperationsGroup(["`Aggregation Operations`"]) mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/QueryOperationsGroup -.-> mongodb/project_fields("`Project Fields`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/query_embedded_documents("`Query Embedded Documents`") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("`Aggregate Group Totals`") subgraph Lab Skills mongodb/find_documents -.-> lab-422089{{"`Project MongoDB Fields`"}} mongodb/query_with_conditions -.-> lab-422089{{"`Project MongoDB Fields`"}} mongodb/project_fields -.-> lab-422089{{"`Project MongoDB Fields`"}} mongodb/query_embedded_documents -.-> lab-422089{{"`Project MongoDB Fields`"}} mongodb/aggregate_group_totals -.-> lab-422089{{"`Project MongoDB Fields`"}} end

Select Include Fields

In this step, you'll learn how to use MongoDB projection to select specific fields when querying documents. Projection allows you to control exactly which fields are returned in your query results.

First, let's start the MongoDB shell and create a sample collection to work with:

mongosh

Once in the MongoDB shell, create a database and add some sample user documents:

use projectlab_database

db.users.insertMany([
    {
        name: "John Doe",
        age: 30,
        email: "[email protected]",
        city: "New York",
        job: "Software Engineer"
    },
    {
        name: "Jane Smith",
        age: 28,
        email: "[email protected]",
        city: "San Francisco",
        job: "Data Scientist"
    },
    {
        name: "Mike Johnson",
        age: 35,
        email: "[email protected]",
        city: "Chicago",
        job: "Product Manager"
    }
])

Now, let's use projection to select only specific fields. To include fields, use 1 in the projection document:

db.users.find({}, { name: 1, age: 1, _id: 0 });

Example output:

[
  { name: 'John Doe', age: 30 },
  { name: 'Jane Smith', age: 28 },
  { name: 'Mike Johnson', age: 35 }
]

Let's break down the projection:

  • { name: 1, age: 1, _id: 0 } means:
    • Include the name field
    • Include the age field
    • Explicitly exclude the _id field (by default, _id is always returned)

By using projection, you can control exactly which fields are returned in your query, reducing unnecessary data transfer and improving query performance.

Specify Exclude Fields

In this step, you'll learn how to exclude specific fields from your MongoDB query results using projection. This technique allows you to remove unwanted fields from the document output.

We'll continue using the users collection we created in the previous step. To exclude fields, use 0 in the projection document:

db.users.find({}, { email: 0, city: 0 });

Example output:

[
  {
    _id: ObjectId("..."),
    name: 'John Doe',
    age: 30,
    job: 'Software Engineer'
  },
  {
    _id: ObjectId("..."),
    name: 'Jane Smith',
    age: 28,
    job: 'Data Scientist'
  },
  {
    _id: ObjectId("..."),
    name: 'Mike Johnson',
    age: 35,
    job: 'Product Manager'
  }
]

Important projection rules to remember:

  • You cannot mix inclusion and exclusion in the same projection (except for _id)
  • _id is the only field you can explicitly exclude while including other fields
  • Using 0 removes the specified fields from the query result

Let's try another example excluding multiple fields:

db.users.find({}, { email: 0, city: 0, _id: 0 });

This query will return documents without the email, city, and _id fields, showing only name, age, and job.

Mix Include Exclude

In this step, you'll learn about the nuanced rules of mixing inclusion and exclusion in MongoDB projections. While MongoDB generally doesn't allow mixing inclusion and exclusion in the same projection, there's a special exception for the _id field.

Let's explore this concept using our existing users collection:

First, let's try an example that demonstrates the general rule:

// This will cause an error
db.users.find({}, { name: 1, email: 0 });

You'll see an error message indicating that you cannot mix inclusion and exclusion projections.

However, _id is a special case. You can include or exclude other fields while explicitly managing the _id field:

db.users.find(
  {},
  {
    _id: 0, // Exclude _id
    name: 1, // Include name
    job: 1 // Include job
  }
);

Example output:

[
  { name: 'John Doe', job: 'Software Engineer' },
  { name: 'Jane Smith', job: 'Data Scientist' },
  { name: 'Mike Johnson', job: 'Product Manager' }
]

Let's try another example with a different combination:

db.users.find(
  {},
  {
    _id: 0, // Exclude _id
    name: 1, // Include name
    age: 1, // Include age
    email: 0 // This would normally cause an error, but _id exception allows it
  }
);

Key takeaways:

  • You cannot mix inclusion and exclusion for regular fields
  • _id is the only field that can be explicitly included or excluded when other fields are being projected
  • Always be explicit about which fields you want to include or exclude

Project Nested Fields

In this step, you'll learn how to project nested fields in MongoDB documents. Nested fields are fields within embedded documents or arrays, which require a slightly different approach to projection.

First, let's update our users collection with more complex, nested documents:

// Clear existing documents
db.users.deleteMany({});

// Insert documents with nested structures
db.users.insertMany([
  {
    name: "John Doe",
    contact: {
      email: "[email protected]",
      phone: {
        mobile: "123-456-7890",
        work: "987-654-3210"
      }
    },
    skills: ["JavaScript", "MongoDB", "React"]
  },
  {
    name: "Jane Smith",
    contact: {
      email: "[email protected]",
      phone: {
        mobile: "234-567-8901",
        work: "876-543-2109"
      }
    },
    skills: ["Python", "Data Science", "Machine Learning"]
  }
]);

To project nested fields, use dot notation:

// Project specific nested fields
db.users.find(
  {},
  {
    name: 1,
    "contact.email": 1,
    "contact.phone.mobile": 1,
    _id: 0
  }
);

Example output:

[
  {
    name: 'John Doe',
    contact: {
      email: '[email protected]',
      phone: { mobile: '123-456-7890' }
    }
  },
  {
    name: 'Jane Smith',
    contact: {
      email: '[email protected]',
      phone: { mobile: '234-567-8901' }
    }
  }
]

You can also project array fields:

// Project first two skills
db.users.find(
  {},
  {
    name: 1,
    skills: { $slice: 2 },
    _id: 0
  }
);

Example output:

[
  {
    name: 'John Doe',
    skills: ['JavaScript', 'MongoDB']
  },
  {
    name: 'Jane Smith',
    skills: ['Python', 'Data Science']
  }
]

Key points about nested field projection:

  • Use dot notation to access nested fields
  • You can project deeply nested fields
  • For arrays, you can use $slice to limit the number of returned elements

Format Output Fields

In this step, you'll learn how to format and transform output fields using MongoDB's projection and aggregation techniques. We'll explore ways to rename, calculate, and modify fields during projection.

First, let's update our users collection with more detailed information:

// Clear existing documents
db.users.deleteMany({});

// Insert documents with more complex data
db.users.insertMany([
  {
    name: "John Doe",
    age: 30,
    salary: 75000,
    department: "Engineering"
  },
  {
    name: "Jane Smith",
    age: 28,
    salary: 85000,
    department: "Data Science"
  },
  {
    name: "Mike Johnson",
    age: 35,
    salary: 95000,
    department: "Management"
  }
]);

Use the $ operator to rename fields during projection:

db.users.find(
  {},
  {
    fullName: "$name",
    yearsOld: "$age",
    annualSalary: "$salary",
    _id: 0
  }
);

Example output:

[
  { fullName: 'John Doe', yearsOld: 30, annualSalary: 75000 },
  { fullName: 'Jane Smith', yearsOld: 28, annualSalary: 85000 },
  { fullName: 'Mike Johnson', yearsOld: 35, annualSalary: 95000 }
]

You can also perform calculations using the $ aggregation operators:

db.users.aggregate([
  {
    $project: {
      name: 1,
      monthlySalary: { $divide: ["$salary", 12] },
      salaryTier: {
        $switch: {
          branches: [
            { case: { $lt: ["$salary", 80000] }, then: "Junior" },
            { case: { $gte: ["$salary", 80000] }, then: "Senior" }
          ],
          default: "Unknown"
        }
      },
      _id: 0
    }
  }
]);

Example output:

[
  {
    name: 'John Doe',
    monthlySalary: 6250,
    salaryTier: 'Junior'
  },
  {
    name: 'Jane Smith',
    monthlySalary: 7083.333333333333,
    salaryTier: 'Senior'
  },
  {
    name: 'Mike Johnson',
    monthlySalary: 7916.666666666667,
    salaryTier: 'Senior'
  }
]

Key points about formatting output fields:

  • Use $ to rename fields during projection
  • Aggregation pipeline allows complex field transformations
  • You can perform calculations and create conditional fields
  • $project stage is powerful for field formatting

Summary

In this lab, you will learn how to use MongoDB's projection feature to select or exclude specific fields when querying documents. You will start by including only the fields you need, then explore excluding unwanted fields, and finally mix include and exclude to customize the output. Additionally, you will learn how to project nested fields and format the output. These techniques allow you to control the data returned by your queries, improving performance and reducing unnecessary data transfer.

Other MongoDB Tutorials you may like