In this part of the Learn Mongo Series, we will learn how to perform projection in mongodb. In mongodb, Projection is selecting on the required fields rather than displaying all the document. For example if my document is having 10 fields and i only want to see 3 of them, then that can be achieved using projections.
1 in all the fields we want to display or
0 in all the fields we don't want to display. _id fields default value is 1 , so if want don't want this field we have
to give 0 in the optional paramter. Examples are given below :
> db.details.find().pretty()
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"),
"name" : "nodejsera",
"age" : "10",
"description" : "Mongodb tuttorial series"
}
{
"_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"),
"age" : "11",
"description" : "learn mongodb",
"name" : "Updated a"
}
{
"_id" : ObjectId("5996f7c3a4b26dc0d6d75c1f"),
"name" : "b",
"age" : "20",
"description" : "this is B"
}
name and _id fields :
> db.details.find({},{"name" : 1})
{ "_id" : ObjectId("5996be4fa4b26dc0d6d75c1c"), "name" : "nodejsera" }
{ "_id" : ObjectId("5996be4fa4b26dc0d6d75c1d"), "name" : "Updated a" }
{ "_id" : ObjectId("5996f7c3a4b26dc0d6d75c1f"), "name" : "b" }
>
_id field on the same collection :
> db.details.find({},{"_id": 0,"name" : 1})
{"name" : "nodejsera" }
{"name" : "Updated a" }
{"name" : "b" }
>
In this part of learn mongo series , we learned about how we can implement projections in mongodb.