MongoDB query to select distinct and count?

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo586.insertOne(
...    {"details": [
...       {
...          "Name":"Chris",
...          "Marks":71
...       },
...       {
...          "Name":"Chris",
...          "Marks":61
...       },
...       {
...          "Name":"David",
...          "Marks":81
...       }
...  
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc7")
}
> db.demo586.insertOne(
... {"details": [
...    {
...       "Name":"Chris",
...       "Marks":71
...    },
...    {
...       "Name":"Carol",
...       "Marks":61
...    },
...    {
...       "Name":"David",
...       "Marks":81
...    }
...
... ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc8")
}

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

> db.demo586.find();

This will produce the following output −

{ "_id" : ObjectId("5e9200fefd2d90c177b5bcc7"), "details" : [
   { "Name" : "Chris", "Marks" : 71 },
   { "Name" : "Chris", "Marks" : 61 },
   { "Name" : "David", "Marks" : 81 }
] }
{ "_id" : ObjectId("5e9200fefd2d90c177b5bcc8"), "details" : [
   { "Name" : "Chris", "Marks" : 71 },
   { "Name" : "Carol", "Marks" : 61 },
   { "Name" : "David", "Marks" : 81 }
] }

Following is the query to select distinctly and count −

> var q= [
...    { "$unwind": "$details" },
...    {
...       "$group": {
...          "_id": {
...             "Name": "$details.Name",
...             "Marks": "$details.Marks"
...          },
...          "count": { "$sum": 1 }
...       }
...    },
...    {
...       "$group": {
...          "_id": "$_id.Name",
...          "distinctV": {
...             "$addToSet": {
...                "value": "$_id.Marks",
...                "numberOfValues": "$count"
...             }
...          }
...       }  
...    },
...    {
...       "$project": {
...          "_id": 0,
...          "Name": "$_id",
...          "distinctV": 1
...       }
...    }
... ];
> db.demo586.aggregate(q);

This will produce the following output −

{ "distinctV" : [ { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Carol" }
{ "distinctV" : [ { "value" : 71, "numberOfValues" : 2 }, { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Chris" }
{ "distinctV" : [ { "value" : 81, "numberOfValues" : 2 } ], "Name" : "David" }
raja
Published on 15-May-2020 06:41:28
Advertisements