MongoDB-Projection

In MongoDB, a projection is the very important due to performance. Selecting only needed data from the document is called projection. Suppose we have a collection EMP and it contains documents with fields Name, Salary, Project, DOJ (Date of joining) and, we have needed only data of Name and Salary to select, here we should avoid selecting whole documents.

Example

Suppose we have a collection EMP as below.


/* 1 */
{
    "_id" : "1",
    "Name" : "Dilip",
    "Salary" : 50000.0,
    "Project" : "Codeafri Mongodb",
    "DOJ" : ISODate("2014-12-01T20:19:55.782Z")
}

/* 2 */
{
    "_id" : "2",
    "Name" : "Vipul",
    "Salary" : 30000.0,
    "Project" : "Codeafri UI",
    "DOJ" : ISODate("2015-11-01T20:19:55.782Z")
}

/* 3 */
{
    "_id" : "3",
    "Name" : "Ashish",
    "Salary" : 100000.0,
    "Project" : "Codeafri Project architect",
    "DOJ" : ISODate("2013-10-01T20:19:55.782Z")
}


In MongoDB, we use find() method to fetch documents, find() method accept the list of fields as a second optional parameter. The list of fields means the fields you wish to retrieve. If it executes without passing parameter then it will fetch all the fields of documents.

Syntax


>db.COLLECTION_NAME.find({},{KEY:1})


KEY:1 means you have to set fields with 0 or 1, if you set fields value 1 means it will appear in the result set and, to hide fields you will set 0.

Query

Please see following query which displays Name and Salary of documents from EMP collection.


db.getCollection('EMP').find({},{"Name":1,"Salary":1})



Output



/* 1 */
{
    "_id" : "1",
    "Name" : "Dilip",
    "Salary" : 50000.0
}

/* 2 */
{
    "_id" : "2",
    "Name" : "Vipul",
    "Salary" : 30000.0
}

/* 3 */
{
    "_id" : "3",
    "Name" : "Ashish",
    "Salary" : 100000.0
}


Hey, what is this? We did not invite to _id, it's displaying here. Don’t be panic, found() method always displays _id when you executed it.
If we don't need _id so please execute the following query.


db.getCollection('EMP').find({},{"Name":1,"Salary":1,"_id":0})



Output



/* 1 */
{
    "Name" : "Dilip",
    "Salary" : 50000.0
}

/* 2 */
{
    "Name" : "Vipul",
    "Salary" : 30000.0
}

/* 3 */
{
    "Name" : "Ashish",
    "Salary" : 100000.0
}



I this article make sense about projection if you want to know more about this please visit this link $(projection).