How to get distinct name and count in MongoDB using PyMongo

余生颓废 提交于 2020-06-17 09:34:12

问题


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",
}

回答1:


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"
  }
]


来源:https://stackoverflow.com/questions/61877635/how-to-get-distinct-name-and-count-in-mongodb-using-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!