fear_matrix
fear_matrix

Reputation: 4960

How to get distinct name and count in MongoDB using PyMongo

I have the below collection as shown below. All I want is the distinct "Name" and the count. For example Betty appears 2 times, so the output I want is Betty:2, Vic:1, Veronica:2. I am able to get the distinct Name by issuing the command "db.Car.find().distinct('Name')" but not sure how to get the count.

{
    "Name": "Betty",
    "Car": "Jeep",
}
{
    "Name": "Betty",
    "Car": "Van",
}
{
    "Name": "Vic",
    "Car": "Ferrari",
}
{
    "Name": "Veronica",
    "Car": "Bus",
}
{
    "Name": "Veronica",
    "Car": "Van",
}

Upvotes: 0

Views: 232

Answers (1)

ngShravil.py
ngShravil.py

Reputation: 5058

You can just use $group to group by Name field and use $sum operator in it to get the Count field.

Something like below:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$Name",
      "Count": {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "Name": "$_id",
      "Count": 1,
      "_id":0
    }
  }
])

The above will produce the following output:

[
  {
    "Count": 2,
    "Name": "Betty"
  },
  {
    "Count": 1,
    "Name": "Vic"
  },
  {
    "Count": 2,
    "Name": "Veronica"
  }
]

Upvotes: 2

Related Questions