Mongodb 通过忽略数组中的重复项来计数文档
每次预约都有一些服务。我要查找每个服务的预约总数 我的文档如下所示:Mongodb 通过忽略数组中的重复项来计数文档,mongodb,mongodb-query,nosql,Mongodb,Mongodb Query,Nosql,每次预约都有一些服务。我要查找每个服务的预约总数 我的文档如下所示: [{ "appointmentTag":"xyz", "services" : [ { "name" : "service1", "estimatedTime":20 }, { "name" : "service2", "estimatedTime":40 } ] }, { "appointmentTag":"abc", "se
[{
"appointmentTag":"xyz",
"services" : [
{
"name" : "service1",
"estimatedTime":20
},
{
"name" : "service2",
"estimatedTime":40
}
]
},
{
"appointmentTag":"abc",
"services" : [
{
"name" : "service2",
"estimatedTime":100
},
{
"name" : "service2",
"estimatedTime":30
}
]
}
db.test.aggregate([
{
"$unwind": "$services"
},
{
"$group": {
"_id": "$services.name",
"appointments": {
"$addToSet": "$appointmentTag"
}
}
},
{
"$project": {
"ServiceName": "$_id","_id":0,
"countOfAppointments": {
"$size": "$appointments"
}
}
}
])
预期产出如下:
{"serviceName":"service1", "count":1}
{"serviceName":"service2", "count":2}
我尝试的查询:
db.appointments.aggregate([
{"$unwind": "$services"},
{"$group": {
"_id": "$services.name",
"count": {"$sum":1}
}}
]);
获得以下结果:
{"serviceName":"service1", "count":1}
{"serviceName":"service2", "count":3}
你做得几乎正确。展开后,当您按serviceName分组而不是计数时,请使用$addToSet of appointmentTag,然后计数该数组。大概是这样的:
[{
"appointmentTag":"xyz",
"services" : [
{
"name" : "service1",
"estimatedTime":20
},
{
"name" : "service2",
"estimatedTime":40
}
]
},
{
"appointmentTag":"abc",
"services" : [
{
"name" : "service2",
"estimatedTime":100
},
{
"name" : "service2",
"estimatedTime":30
}
]
}
db.test.aggregate([
{
"$unwind": "$services"
},
{
"$group": {
"_id": "$services.name",
"appointments": {
"$addToSet": "$appointmentTag"
}
}
},
{
"$project": {
"ServiceName": "$_id","_id":0,
"countOfAppointments": {
"$size": "$appointments"
}
}
}
])
你做得几乎正确。展开后,当您按serviceName分组而不是计数时,请使用$addToSet of appointmentTag,然后计数该数组。大概是这样的:
[{
"appointmentTag":"xyz",
"services" : [
{
"name" : "service1",
"estimatedTime":20
},
{
"name" : "service2",
"estimatedTime":40
}
]
},
{
"appointmentTag":"abc",
"services" : [
{
"name" : "service2",
"estimatedTime":100
},
{
"name" : "service2",
"estimatedTime":30
}
]
}
db.test.aggregate([
{
"$unwind": "$services"
},
{
"$group": {
"_id": "$services.name",
"appointments": {
"$addToSet": "$appointmentTag"
}
}
},
{
"$project": {
"ServiceName": "$_id","_id":0,
"countOfAppointments": {
"$size": "$appointments"
}
}
}
])