聚合:我如何计算该值为真值的键数?
我在MongoDB中有很多文档,看起来像这样:
[
{
name: "steve",
accountFeatures: {word: true, excel: false, powerpoint: true}
},
{
name: "john",
accountFeatures: {word: false, excel: true, powerpoint: true, notes: true}
},
{
name: "rick",
accountFeatures: {word: true, excel: false, powerpoint: true}
}
]
我想运行一个聚合以找出对象中的每个键都设置为true(实际数据中还有更多键),所以样本数据的预期输出将是:
{
"res": {
"excel": 1,
"notes": 1,
"powerpoint": 3,
"word": 2
}
}
这可能吗?到目前为止,我所能做的就是这样:
[
{
'$project': {
'_id': 0,
'accountFeatures': 1
}
]
I have a load of documents in mongodb which look something like this:
[
{
name: "steve",
accountFeatures: {word: true, excel: false, powerpoint: true}
},
{
name: "john",
accountFeatures: {word: false, excel: true, powerpoint: true, notes: true}
},
{
name: "rick",
accountFeatures: {word: true, excel: false, powerpoint: true}
}
]
I want to run an aggregation to find out how many of each of the keys in the objects are set to true (there are many more keys in the actual data), so the expected output for the sample data would be:
{
"res": {
"excel": 1,
"notes": 1,
"powerpoint": 3,
"word": 2
}
}
Is this possible? So far all I can think to do is this:
[
{
'$project': {
'_id': 0,
'accountFeatures': 1
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
$ objectToArray
和$ unvind
,它将允许我们$ group
by the键:$ objecttoArray
提取密钥$ filter
仅保留true
ands$ UNTIND
将键与不同文档的键$ group
将计算每个键游乐场示例
You can use
$objectToArray
and$unwind
which will allow us$group
by the keys:$objectToArray
to extract the keys$filter
to keep only thetrue
ones$unwind
to separate the keys to different documents$group
to count each keyPlayground example