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 }