To retrieve only specific columns from the MongoDB documents there are some different logics compare to SQL,
Two different ways to get the specific columns
- Including only the columns we need ( Giving ColumnName : true ( or ) 1 )
- Excluding all other columns (Giving ColumnName : false ( or ) 1 )
Initial Data
{ "Name" : "Venki","Department" : "CSE","Languages" :[ { "speak" : "english","Write" : "telugu", "Expert" : "malayalam" } ] }
{ "Name" : "Rahul","Department" : "EEE","Languages" :[ { "speak" : "Bengali","Write" : "telugu", "Expert" : "malayalam" } ] }
{ "Name" : "Brajesh","Department" : "CSE","Languages" :[ { "speak" : "Gujarathi", "Write" : "telugu", "Expert" : "malayalam" } ] }
{ "Name" : "vikram", "Department" : "CSE", "Languages" : [ { "speak" : "Tamil", "Write" : "telugu", "Expert" : "English" } ] }
Example of retrieving all the Names from the StudentDetails collection
db.studentDetails.find({},{Name:true,_id:false})
output will be as
{ "Name" : "Venki"}
{ "Name" : "Rahul"}
{ "Name" : "Brajesh"}
{ "Name" : "vikram"}
Example to get only name and department from Mongo Documents
db.studentDetails.find({},{_id:false,Languages:false})
output will be as
{ "Name" : "Venki", "Department" : "CSE" }
{ "Name" : "Rahul", "Department" : "EEE" }
{ "Name" : "Brajesh", "Department" : "CSE" }
{ "Name" : "vikram", "Department" : "CSE" }
Example of retrieving the name and department of name ‘venki’
db.studentDetails.find({Name:'Venki'},{Languages:false,_id:false})
output will be as
{ "Name" : "Venki", "Department" : "CSE" }