问题
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