MongoDB Projection
In the previous tutorials, we learned how to use criteria while Querying document to get the selected documents from the collection. In this tutorial, we will learn another interesting topic of MongoDB which is MongoDB Projection. This is used when we want to get the selected fields of the documents rather than all fields.
For example, we have a collection where we have stored documents that have the fields: student_name, student_id, student_age but we want to see only the student_id of all the students then in that case we can use projection to get only the student_id.
Syntax:
db.collection_name.find({},{field_key:1 or 0})
Do not worry about the syntax now, we will see an example to understand this.
MongoDB Projection Example
Lets take an example to understand the Projection in MongoDB. We have a collection named
studentdata
that has following documents.> db.studentdata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"student_name" : "Steve",
"student_id" : 2002,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
"student_age" : 23
}
To get only the student_id for all the documents, we will use the Projection like this:
> db.studentdata.find({}, {"_id": 0, "student_id": 1})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
Value 1 means show that field and 0 means do not show that field. When we set a field to 1 in Projection other fields are automatically set to 0, except _id, so to avoid the _id we need to specifically set it to 0 in projection. The vice versa is also true when we set few fields to 0, other fields set to 1 automatically(see the below example)
Another way of doing the same thing:
> db.studentdata.find({}, {"_id": 0, "student_name": 0, "student_age": 0})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
Important Note:
Some of you may get this error while using Projection in Query:
Some of you may get this error while using Projection in Query:
Error: error: {
"ok" : 0,
"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
"code" : 2,
"codeName" : "BadValue"
}
This happens when you set some fields to 0 and other to 1, in other words you mix inclusion and exclusion, the only exception is the _id field. for example: The following Query would produce this error:
db.studentdata.find({}, {"_id": 0, "student_name": 0, "student_age": 1})
This is because we have set student_name to 0 and other field student_age to 1. We can’t mix these. You either set those fields that you don’t want to display to 0 or set the fields to 1 that you want to display.
0 comments:
Post a Comment