【发布时间】:2018-10-16 11:22:37
【问题描述】:
我已经用不同的组合来解决这个问题了一段时间 $project, $match, $unwind 在 Mongodb 聚合管道中。我的数据是这样的:
{
"flow":[
{"y":1},
{"y":69696},
{"y":3}
]
}
{
"flow":[
{"y":4},
{"y":69632},
{"y":6},
{"y":7},
{"y":8}
]
}
我想根据 flow.y 是否设置了第 16 位来对流数组元素进行分组。我想返回值的总和(没有设置位)和匹配元素的计数。因此,对于上面的示例,我要检索:
[
{ "bitset": {
"_id":null,
"count":2,
"y_total":8256
},
"bitunset": {
"_id":null,
"count":6,
"y_total":29
},
}
]
我可以在两个单独的聚合调用中检索信息,但想将它们组合起来。
db.collection.aggregate([
{$unwind: {path: "$flow"}},
{$match: {"flow.y": { $bitsAllSet: 65536 }}},
{$group: {
_id: null,
count: { $sum: 1 },
y_total: {$sum: "$flow.y"}
}}
我也试过了:
db.collection.aggregate([
{$unwind: {path: "$flow"}},
{$match: {$or: [{"flow.y": { $bitsAllSet: 65536 }},
{"flow.y": { $bitsAllClear: 65536 }}]}},
{$group: {
_id: null,
count: { $sum: 1 },
y_total: {$sum: "$flow.y"}
}}
如果我可以为 $or 运算符的结果设置别名就好了。 数据库版本 v3.6.5
【问题讨论】:
-
如果我可以指定两个不同的返回字段名而不是两个不同的值,$cond 会很有用。我试过 {$cond: [{"flow.y": { $bitsAllSet: 65536 }}, 1, 0]} } 但它错误“参数必须是聚合管道运算符”
标签: mongodb mongoose aggregation-framework