- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to return a list of specific values from a MongoDB query?
Yes, using map(). Let us first create a collection with documents −
> dblistOfSpecificValuesDemoinsertOne({"StudentName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefcc8fef71edecf6a1f6bb") } > dblistOfSpecificValuesDemoinsertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefcc94ef71edecf6a1f6bc") } > dblistOfSpecificValuesDemoinsertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefcc98ef71edecf6a1f6bd") } > dblistOfSpecificValuesDemoinsertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefcc9cef71edecf6a1f6be") }
Following is the query to display all documents from a collection with the help of find() method −
> dblistOfSpecificValuesDemofind();
Output
{ "_id" : ObjectId("5cefcc8fef71edecf6a1f6bb"), "StudentName" : "John" } { "_id" : ObjectId("5cefcc94ef71edecf6a1f6bc"), "StudentName" : "Chris" } { "_id" : ObjectId("5cefcc98ef71edecf6a1f6bd"), "StudentName" : "Robert" } { "_id" : ObjectId("5cefcc9cef71edecf6a1f6be"), "StudentName" : "David" }
Following is the query to return a list of specific values from a query −
> dblistOfSpecificValuesDemofind()map(function(myDocument){ return myDocumentStudentName });
Output
[ "John", "Chris", "Robert", "David" ]
Advertisements