mongodb - 使用带有条件的 $group 管道进行聚合
问题描述
这是我的数据,有 6 条记录...
{
_id: 1,
entityProfiles:['company', 'provider']
},
{
_id: 2,
entityProfiles:['company']
},
{
_id: 3,
entityProfiles:['provider']
},
{
_id: 4,
entityProfiles:[]
},
{
_id: 5,
entityProfiles:null
},
{
_id: 6,
},
我需要知道总数,有多少 entityProfiles 有“提供者”,有多少没有使用 $group 和/或 $project 管道。我预料到这...
{
_id: 'all',
count: 6
},
{
_id: 'providers',
count: 2
},
{
_id: 'nonProviders',
count: 4
},
... 或这个...
{
_id: null,
all: 6,
providers: 2,
nonProviders: 4
},
解决方案
试试这个:
db.collection.aggregate([
{
$group: {
_id: null,
all: {
$sum: 1
},
providers: {
$sum: {
$cond: [
{
$in: [
"provider",
{
$ifNull: [ "$entityProfiles", [] ]
}
]
},
1,
0
]
}
},
nonProviders: {
$sum: {
$cond: [
{
$in: [
"provider",
{
$ifNull: [ "$entityProfiles", [] ]
}
]
},
0,
1
]
}
}
}
}
])
推荐阅读
- java - 在异步任务上获得 ANR
- python - Python 的 pbkdf2_sha256.verify 的 NodeJS 实现
- dropbox - 仅使用应用程序密钥/秘密在 Dropbox 上下载我的文件?
- angular - Angular / Ionic Framework - 尝试绑定到 *ngFor 循环中的对象
- java - Java说邮件已经发送,但实际上没有
- css - 如何将 2 个不透明的元素连接起来看起来像一个?
- r - 向矩阵中的一组列添加另一个标签
- java - 将单独的文档作为一个对象检索
- objective-c - 从临时目录移动时无法重命名文件
- javascript - VueJS:无法读取未定义的属性“名称””