Count the number of duplicate elements in MongoDB

Viewed 557

I have the collection blow in mongodb:

{
    "Id": "5",
    "Group": [
        {
            "Name": "frank",
            "Roll": "123"
        }
    ]
},
{
    "Id": "6",
    "Group": [
        {
            "Name": "John",
            "Roll": "124"
        }
    ]
},
{
    "Id": "7",
    "Group": [
        {
            "Name": "John",
            "Roll": "125"
        }
    ]
}

The name "John" appears twice. I would like to display the number of each name that appears more than once:

{"Name": "John", "Count":2 }
1 Answers

You can use this aggregation query:

  • First $unwind to deconstruct the array and get all values as an object.
  • Then group by the name and $sum 1 for each name.
  • And then $match to get those values which exists more than one time (i.e. are repeated)
  • And last stage is to output values you want, in this case Name and Count.
db.collection.aggregate([
  {
    "$unwind": "$Group"
  },
  {
    "$group": {
      "_id": "$Group.Name",
      "Count": {
        "$sum": 1
      },
      
    }
  },
  {
    "$match": {
      "Count": {
        "$gt": 1
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "Name": "$_id",
      "Count": 1
    }
  }
])

Example here

Related