Specify a return format for data in MongoDB


Take the help of $addToSet in MongoDB to specify a return format. Let us create a collection with documents −

> db.demo207.insertOne({"FavouriteTechnology":"Spring Boot"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8e7a03d395bdc21346f1")
}
> db.demo207.insertOne({"FavouriteTechnology":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8e8f03d395bdc21346f2")
}
> db.demo207.insertOne({"FavouriteTechnology":"Groovy"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d8ea603d395bdc21346f3")
}

Display all documents from a collection with the help of find() method −

> db.demo207.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d8e7a03d395bdc21346f1"), "FavouriteTechnology" : "Spring Boot" }
{ "_id" : ObjectId("5e3d8e8f03d395bdc21346f2"), "FavouriteTechnology" : "MongoDB" }
{ "_id" : ObjectId("5e3d8ea603d395bdc21346f3"), "FavouriteTechnology" : "Groovy" }

Following is the query to specify return format −

> db.demo207.aggregate([
...   {
...      "$group": {
...         "_id": 0,
...         "FavouriteTechnology": {
...            "$addToSet": "$FavouriteTechnology"
...         }
...      }
...   },
...   {
...      "$project": {
...         "_id": 0,
...         "FavouriteTechnology": 1
...      }
...   }
...]);

This will produce the following output −

{ "FavouriteTechnology" : [ "MongoDB", "Groovy", "Spring Boot" ] }

Updated on: 27-Mar-2020

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements