- 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
Projection result as an array of selected items in MongoDB?
Use the distinct() for this, since it finds the distinct values for a specified field across a single collection or view and returns the results in an array.
Let us first create a collection with documents −
> db.projectionListDemo.insertOne({"_id":"1","Subject":["MongoDB","MySQL","Java"]}); { "acknowledged" : true, "insertedId" : "1" } > db.projectionListDemo.insertOne({"_id":"2","Subject":["MongoDB","C","C++"]}); { "acknowledged" : true, "insertedId" : "2" } > db.projectionListDemo.insertOne({"_id":"3","Subject":["Java","Python"]}); { "acknowledged" : true, "insertedId" : "3" }
Display all documents from a collection with the help of find() method −
> db.projectionListDemo.find().pretty();
Output
{ "_id" : "1", "Subject" : [ "MongoDB", "MySQL", "Java" ] } { "_id" : "2", "Subject" : [ "MongoDB", "C", "C++" ] } { "_id" : "3", "Subject" : [ "Java", "Python" ] }
Now, let us get result as an array of selected items −
> db.projectionListDemo.distinct('_id', {'Subject' : 'MongoDB'});
Output
[ "1", "2" ]
Advertisements