MongoDb Tutorial

Day 8 : Projection in MongoDB








Mongodb tutorial series

Overview

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.

Let's perform projection

  • Find() method : find method in mongodb can take up an additional argument which can be used to perform the process of projection in mongodb. In this optional parameter field, we can pass the value 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 :
    Consider the following collection :
    											
    										
    > 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"
    }
    												
    										

    Now let's only display its 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" }
    >
    									
    											
    										

    Now suppose you dont want the _id field on the same collection :

    											
    > db.details.find({},{"_id": 0,"name" : 1})
    {"name" : "nodejsera" }
    {"name" : "Updated a" }
    {"name" : "b" }
    >
    									
    											
    										

Hurray !! Mission Accomplished. We have successfully implemented projection in mongodb.

Summary

In this part of learn mongo series , we learned about how we can implement projections in mongodb.