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" ] }

Updated on: 30-Jul-2019

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements