Projections in MongoDB - Selecting specific fields of documents in collection in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >


Projections in MongoDB - Selecting specific fields of documents in collection in MongoDB


First, Let's create new collection and insert document in it >
> db.employee.insert({_id : 1,  firstName:"ankit"})
> db.employee.insert({_id : 2,  firstName:"ankit", salary : 1000 })
> db.employee.insert({_id : 3,  firstName:"sam", salary : 2000 })
> db.employee.insert({_id : 4,  firstName:"neh", salary : 3000 })
First line above will create table (or collection) (if table already exists it will insert documents in it).


1) Display only firstName field of document of collection using find() method>
> db.employee.find( {}, {firstName : 1})


Output>
{ "_id" : 1, "firstName" : "ankit" }
{ "_id" : 2, "firstName" : "ankit" }
{ "_id" : 3, "firstName" : "sam" }
{ "_id" : 4, "firstName" : "neh" }
By default _id field is always shown.


2) Display only firstName and salary field of document of collection using find() method>
> db.employee.find( {}, {firstName : 1, salary : 1})
Output>
{ "_id" : 1, "firstName" : "ankit" }
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }
{ "_id" : 4, "firstName" : "neh", "salary" : 3000 }
By default _id field is always shown.


3) Display only firstName and salary field of document of collection, But avoid _id field to be displayed using find() method>
> db.employee.find( {}, { _id :0, firstName : 1, salary : 1})
Output>
{ "firstName" : "ankit" }
{ "firstName" : "ankit", "salary" : 1000 }
{ "firstName" : "sam", "salary" : 2000 }
{ "firstName" : "neh", "salary" : 3000 }


4) FIND Example > Display only firstName and salary field of document of collection where salary > 1000, But avoid _id field to be displayed using find() method>
> db.employee.find( { salary : {$gt : 1000} }, { _id :0, firstName : 1, salary : 1})
Output>
{ "firstName" : "sam", "salary" : 2000 }
{ "firstName" : "neh", "salary" : 3000 }




5) SUMMARY>
So in this mongoDB tutorial we learned about Projections in MongoDB - Selecting specific fields of documents in collection in MongoDB.


Display only firstName field of document of collection using find() method>
> db.employee.find( {}, {firstName : 1})


Display only firstName and salary field of document of collection using find() method>
> db.employee.find( {}, {firstName : 1, salary : 1})


Display only firstName and salary field of document of collection, But avoid _id field to be displayed using find() method>
> db.employee.find( {}, { _id :0, firstName : 1, salary : 1})


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :