Group all documents with common fields in MongoDB?


For this, use the $addToSet operator. Let us first create a collection with documents −

> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":1,
      "UserName":"Carol"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51200")
}
> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":2,
      "UserName":"David"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51201")
}
>
> db.findDocumentWithCommonFieldsDemo.insertOne(
   {
      "UserId":1,
      "UserName":"Sam"
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdf8ebebf3115999ed51202")
}

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

> db.findDocumentWithCommonFieldsDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cdf8ebebf3115999ed51200"), "UserId" : 1, "UserName" : "Carol" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51201"), "UserId" : 2, "UserName" : "David" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51202"), "UserId" : 1, "UserName" : "Sam" }

Following is the query to find all documents with common fields in MongoDB −

> db.findDocumentWithCommonFieldsDemo.aggregate({$group : {_id : "$UserId", "UserDetails": {$addToSet : "$UserName"}}});

This will produce the following output −

{ "_id" : 2, "UserDetails" : [ "David" ] }
{ "_id" : 1, "UserDetails" : [ "Sam", "Carol" ] }

Updated on: 30-Jul-2019

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements