- Trending Categories
- 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 query in MongoDB?
To return a list of specific values, use map(). Let us create a collection with documents −
> db.demo195.insertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3f203d395bdc21346d4") } > db.demo195.insertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3f703d395bdc21346d5") } > db.demo195.insertOne({"Subject":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3af3fa03d395bdc21346d6") }
Display all documents from a collection with the help of find() method −
> db.demo195.find();
This will produce the following output −
{ "_id" : ObjectId("5e3af3f203d395bdc21346d4"), "Subject" : "MySQL" } { "_id" : ObjectId("5e3af3f703d395bdc21346d5"), "Subject" : "MongoDB" } { "_id" : ObjectId("5e3af3fa03d395bdc21346d6"), "Subject" : "Java" }
Following is the query to return a list of specific values from a query −
> db.demo195.find().map(function(doc){ return doc.Subject });
This will produce the following output −
[ "MySQL", "MongoDB", "Java" ]
Advertisements