mongodb - 如何在嵌入式文档上查询 $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}})
解决方案
$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
推荐阅读
- html - mat-grid-list 未对齐的 mat-grid-tiles
- android - BluetoothManager getConenctedDevices 返回一个空数组
- python - 如果我尝试在 Python 中使用 IF LIST == 'value' 会出现错误吗?
- swiftui - SearchBar 中的 NavigationView 在更改视图 ID 后是透明的
- php - Laravel 8 - 无法启动新进程
- java - 具有值作为字符串的构造函数参数如何传递给接受整数的构造函数?
- google-app-engine - 如何配置 AppEngine 使用的 ObjectMapper
- c - 如何使用 C 在结构中重复输入数据?
- javascript - 为什么我的 redux 状态为 null 但在控制台中一切正常
- java - 单击 JButton 三次后 Swing GUI 冻结