WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MongoDB · Basic · question 11 of 100

How can you project specific fields while querying data in MongoDB?

📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

In MongoDB, we can use the ‘project‘ method to specify which fields to retrieve while querying data.

Consider a MongoDB collection ‘students‘ with the following documents:

{
    "_id" : ObjectId("614b0e3e3fe1e7bf473990bc"),
    "name" : "Alice",
    "age" : 22,
    "gender" : "female",
    "course" : "mathematics"
}
{
    "_id" : ObjectId("614b0e513fe1e7bf473990bd"),
    "name" : "Bob",
    "age" : 20,
    "gender" : "male",
    "course" : "history"
}

To query for documents with specific fields projected, we can use the ‘project‘ method. For example, to retrieve only the ‘name‘ field:

db.students.find({}, {name: 1})

This will return the following result:

{ "_id" : ObjectId("614b0e3e3fe1e7bf473990bc"), "name" : "Alice" }
{ "_id" : ObjectId("614b0e513fe1e7bf473990bd"), "name" : "Bob" }

In the second argument of the ‘find‘ method, we specify which fields to include (‘name‘ in this case) and set the value to ‘1‘ to tell MongoDB to include the field. If we wanted to exclude a field, we could set the value to ‘0‘.

We can also project multiple fields using the same syntax. For example:

db.students.find({}, {name: 1, age: 1})

This will return the following result:

{ "_id" : ObjectId("614b0e3e3fe1e7bf473990bc"), "name" : "Alice", "age" : 22 }
{ "_id" : ObjectId("614b0e513fe1e7bf473990bd"), "name" : "Bob", "age" : 20 }

Note that we can also use the ‘_id‘ field to project or exclude. By default, MongoDB includes the ‘_id‘ field in all query results. To exclude the ‘_id‘ field, we can set its value to ‘0‘. For example:

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

This will return the following result:

{ "name" : "Alice", "age" : 22 }
{ "name" : "Bob", "age" : 20 }
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MongoDB interview — then scores it.
📞 Practice MongoDB — free 15 min
📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

All 100 MongoDB questions · All topics