- 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
Specify return format in MongoDB to return the values as an array?
Use aggregation for this and add the values to an array using the $group and $addToSet operator
Let us first create a collection with documents −
> dbspecifyReturnFormatDemoinsertOne({"Subject":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefd364ef71edecf6a1f6c0") } > dbspecifyReturnFormatDemoinsertOne({"Subject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefd369ef71edecf6a1f6c1") } > dbspecifyReturnFormatDemoinsertOne({"Subject":"SQL Server"}); { "acknowledged" : true, "insertedId" : ObjectId("5cefd36fef71edecf6a1f6c2") }
Following is the query to display all documents from a collection with the help of find() method −
> dbspecifyReturnFormatDemofind();
Output
{ "_id" : ObjectId("5cefd364ef71edecf6a1f6c0"), "Subject" : "MongoDB" } { "_id" : ObjectId("5cefd369ef71edecf6a1f6c1"), "Subject" : "MySQL" } { "_id" : ObjectId("5cefd36fef71edecf6a1f6c2"), "Subject" : "SQL Server" }
Following is the query to specify return format −
> dbspecifyReturnFormatDemoaggregate([ { "$group": { "_id": 0, "Subject": { "$addToSet": "$Subject" } } }, { "$project": { "_id": 0, "Subject": 1 } } ]);
Output
{ "Subject" : [ "SQL Server", "MySQL", "MongoDB" ] }
Advertisements
To Continue Learning Please Login
Login with Google