Getting a list of values by using MongoDB $group?


To get a list of values, use $group aggregation along with $push operator. Let us first create a collection with documents −

> db.groupByDemo.insertOne({"UserName":"John","Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd69f0457806ebf1256f136")
}
> db.groupByDemo.insertOne({"UserName":"Larry","Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd69f0657806ebf1256f137")
}
> db.groupByDemo.insertOne({"UserName":"John","Subject":"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd69f0d57806ebf1256f138")
}
> db.groupByDemo.insertOne({"UserName":"John","Subject":"C"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd69f1357806ebf1256f139")
}
> db.groupByDemo.insertOne({"UserName":"Larry","Subject":"SQL Server"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd69f1c57806ebf1256f13a")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.groupByDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd69f0457806ebf1256f136"),
   "UserName" : "John",
   "Subject" : "MongoDB"
}
{
   "_id" : ObjectId("5cd69f0657806ebf1256f137"),
   "UserName" : "Larry",
   "Subject" : "MySQL"
}
{
   "_id" : ObjectId("5cd69f0d57806ebf1256f138"),
   "UserName" : "John",
   "Subject" : "Java"
}
{
   "_id" : ObjectId("5cd69f1357806ebf1256f139"),
   "UserName" : "John",
   "Subject" : "C"
}
{
   "_id" : ObjectId("5cd69f1c57806ebf1256f13a"),
   "UserName" : "Larry",
   "Subject" : "SQL Server"
}

Following is the query to get list of values by using $group and $push −

> db.groupByDemo.aggregate({$group: { '_id': '$UserName', 'Subject': { $push: '$Subject'}}});

This will produce the following output −

{ "_id" : "Larry", "Subject" : [ "MySQL", "SQL Server" ] }
{ "_id" : "John", "Subject" : [ "MongoDB", "Java", "C" ] }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements