如何使用 PyMongo 在 MongoDB 中获取不同的名称和计数 [英] How to get distinct name and count in MongoDB using PyMongo
问题描述
我有以下集合,如下所示.我想要的只是不同的名称"和计数.例如 Betty 出现了 2 次,所以我想要的输出是 Betty:2、Vic:1、Veronica:2.我可以通过发出命令db.Car.find().distinct('Name')"来获取不同的名称,但不确定如何获取计数.
<代码>{"姓名": "贝蒂","汽车": "吉普",}{"姓名": "贝蒂","车": "货车",}{"姓名": "维克",汽车":法拉利",}{"名称": "维罗妮卡","汽车": "公共汽车",}{"名称": "维罗妮卡","车": "货车",}
你可以只使用 $group
按 Name
字段分组并使用 $sum
运算符以获取 Count
字段.
类似于以下内容:
db.collection.aggregate([{$组":{"_id": "$Name",数数": {$sum":1}}},{$项目":{"名称": "$_id",计数":1,"_id":0}}])
以上将产生以下输出:
<预><代码>[{计数":2,姓名":贝蒂"},{计数":1,姓名":维克"},{计数":2,名称":维罗妮卡"}]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",
}
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"
}
]
这篇关于如何使用 PyMongo 在 MongoDB 中获取不同的名称和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!