MongoDB Projection

Mongodb Projection is used when we want the selected fields of documents instead of all fields.

MongoDB Projection Syntax :

The syntax of the MongoDB Projection is −

 
   
\\Syntax of MongoDB Projection

db.collection_name.find({},{field_key:1 or 0})



MongoDB Projection Example :

The Example of the MongoDB Projection is −

\\Example of Projection in MongoDB
\\employee :- collection_name
> db.employee.find().pretty()
{
        "_id" : ObjectId("59bf63380be1d7770c3982af"),
        "employee_name" : "Rajesh",
        "employee_id" : 2002,
        "employee_age" : 24
}
{
        "_id" : ObjectId("59bf63500be1d7770c3982b0"),
        "employee_name" : "Jugal",
        "employee_id" : 2003,
        "employee_age" : 25
}
{
        "_id" : ObjectId("59bf63650be1d7770c3982b1"),
        "employee_name" : "Yash",
        "employee_id" : 2004,
        "employee_age" : 23
}

-------------------
-------------------


\\To get only the employee_id for all the documents,

> db.employee.find({}, {"_id": 0, "employee_id": 1})
{ "employee_id" : 2002 }
{ "employee_id" : 2003 }
{ "employee_id" : 2004 }
 

Note:The value 1 means show the field and 0 means not to show the field.In projection if we set any field 1 than automatically all other fields becoms 0. So as we can see that we have selected fields from documents (employee_id), so only employee_id will be shown in the output.





Visit :


Discussion


* You must be logged in to add comment.