我有以下格式的文档集合:
{
"_id" : ObjectId("abc"),
"mobile" : "123456789",
"channels" : [
{
"name" : "email.xz",
"type" : "a",
"properties" : [
{
"provider" : "outlook"
}
]
},
{
"name" : "sms",
"type" : "sms"
}
],
}
我需要找到至少具有一个名称以“ .xz”结尾的通道的客户,但前提是提供者存在且具有值,并返回每个通道的客户数。例如:
email.xz = 10
sms.xz = 5
push.xz = 7
我尝试使用下面的聚合函数,但是它得出了所有符合条件的客户。
db.consumers.aggregate(
{$match: {"channels.name": {$regex: ".xz$"},
"notificationChannels.properties.provider": { $exists: true }}},
{$group: {_id: "channels.name"},
count: {$sum: 1}})
$unwind
数组,然后$match
再次以相同的方式。第一个匹配项只是选择文档,并且您要过滤:
db.consumers.aggregate(
{ $match: {
"channels.name": {$regex: ".xz$"},
"channels.properties.provider": { $exists: true }
}},
{ $unwind: "$channels" },
{ $match: {
"channels.name": {$regex: ".xz$"},
"channels.properties.provider": { $exists: true }
}},
{ $group:{
"_id": "$channels.name",
"count": {$sum: 1}
}}
)
由于您$group
要从阵列“内部”使用键,$unwind
因此无论如何都需要它。由于您只想要符合条件的数组条目,因此使用a的唯一方法$regex
是$match
在$unwind
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句