首页 > 解决方案 > 如何在嵌入式文档上查询 $regex 以计算不同的值

问题描述

我有一个包含以下格式的文档的集合:

{ 
    "_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}})

标签: mongodbaggregation-framework

解决方案


$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


推荐阅读