Syntax error MongoDB query for counting the distinct values across all documents?

MongoDB query for counting the distinct values across all documents?



For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo718.insertOne(
...    {
...       "id":101,
...       "details":
...       {
...          "OtherDetails": ["Chris", "Mike", "Sam"], "GroupName": ["Group-1"], "Info": []
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaae25843417811278f5880")
}
> db.demo718.insertOne(
...    {
...       "id":102,
...       "details":
...       {
...          "OtherDetails": ["Chris", "David"], "GroupName": ["Group-1"], "Info": []
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaae25943417811278f5881")
}

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

> db.demo718.find();

This will produce the following output −

{ "_id" : ObjectId("5eaae25843417811278f5880"), "id" : 101, "details" : { "OtherDetails" : [ "Chris", "Mike", "Sam" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }
{ "_id" : ObjectId("5eaae25943417811278f5881"), "id" : 102, "details" : { "OtherDetails" : [ "Chris", "David" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }

Following is the query to count the distinct values across all documents −

> db.demo718.aggregate([
...    {
...       $unwind: "$details.GroupName"
...    },
...    {
...       $match: {
...          "details.GroupName": "Group-1"
...       }
...    },
... {
...    $unwind: "$details.OtherDetails"
... },
... {
...    $group: {
...       _id: "$details.GroupName",
...       OtherDetailsUnique: {
...          $addToSet: "$details.OtherDetails"
...       }
...    }
... },
... {
...    $project: {
...       _id : 0,
...       GROUP_NAME: "$_id",
...       OtherDetailsUniqueCount: {
...       $size: "$OtherDetailsUnique"
...    }
... }
... }
... ])

This will produce the following output −

{ "GROUP_NAME" : "Group-1", "OtherDetailsUniqueCount" : 4 }
Updated on: 2020-05-14T10:22:06+05:30

450 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements