
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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