 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to return specific fields from an array?
To return specific fields, use aggregate $project. Let us first create a collection with documents −
> db.returnSpecificFieldDemo.insertOne(    {       "StudentId":1,       "StudentDetails": [          {             "StudentName":"Larry",             "StudentAge":21,             "StudentCountryName":"US"          },          {             "StudentName":"Chris",             "StudentAge":23,             "StudentCountryName":"AUS"          }       ]    } ); {    "acknowledged" : true,    "insertedId" : ObjectId("5ce23d3236e8b255a5eee943") } Following is the query to display all documents from a collection with the help of find() method −
> db.returnSpecificFieldDemo.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5ce23d3236e8b255a5eee943"),    "StudentId" : 1,    "StudentDetails" : [       {          "StudentName" : "Larry",          "StudentAge" : 21,          "StudentCountryName" : "US"       },       {          "StudentName" : "Chris",          "StudentAge" : 23,          "StudentCountryName" : "AUS"       }    ] } Following is the query to return specific fields from an array −
> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]); This will produce the following output −
{ "StudentId" : 1, "StudentCountryName" : "AUS" }Advertisements
 