
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Questions & Answers
- MongoDB query to return only specific fields (phone numbers) in the form of an array?
- MongoDB query to sum specific fields
- MongoDB query to get only specific fields in nested array documents?
- How to query a document in MongoDB comparing fields from an array?
- How to project specific fields from a document inside an array in Mongodb?
- MongoDB query to get record beginning with specific element from an array?
- Query an array in MongoDB to fetch a specific value
- MongoDB query to update selected fields
- MongoDB query to concatenate values of array with other fields
- Is it possible to return a list of specific values from a MongoDB query?
- MongoDB query to find data from an array inside an object?
- Sort array in MongoDB query and project all fields?
- Update only specific fields in MongoDB?
- MongoDB query to match and remove element from an array?
- MongoDB inverse of query to return all items except specific documents?
Advertisements