【问题标题】:Alias multiple $match conditions on single field单个字段上的多个 $match 条件的别名
【发布时间】: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

【问题讨论】:

标签: mongodb mongoose aggregation-framework


【解决方案1】:

这是基于$facet 的解决方案:

db.collection.aggregate([{
    $unwind: "$flow"
}, {
    $facet: {
        "bitset": [{
                $match: { "flow.y": { $bitsAllSet: 65536 } }
            }, {
                $group: {
                    _id: null,
                    count: { $sum: 1 },
                    y_total: {$sum: {$subtract: [ "$flow.y", 65536 ] }}
                }
            }
        ],
        "bitunset": [{
                $match: { "flow.y": { $bitsAllClear: 65536 } }
            }, {
                $group: {
                    _id: null,
                    count: { $sum: 1 },
                    y_total: { $sum: "$flow.y" }
                }
            }
        ]
    }
}])

或者没有$group 阶段:

db.collection.aggregate([{
    $unwind: "$flow"
}, {
    $facet: {
        "bitset": [{
                $match: { "flow.y": { $bitsAllSet: 65536 } }
            }
        ],
        "bitunset": [{
                $match: { "flow.y": { $bitsAllClear: 65536 } }
            }
        ]
    }
}, {
    $project: {
        y_count_set: { $size: "$bitset.flow.y" },
        y_total_set: { $subtract: [ { $sum: "$bitset.flow.y" }, { $multiply: [ { $size: "$bitset.flow.y" }, 65536 ] } ] },
        y_count_unset: { $size: "$bitunset.flow.y" },
        y_total_unset: { $sum: "$bitunset.flow.y" }
    }
}])

【讨论】:

  • 啊,谢谢你的例子。我试图从 $facet 子管道中 $unwind 结果并对其执行聚合。哪个行不通。
猜你喜欢
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 2020-08-02
  • 2012-03-04
  • 2011-11-18
相关资源
最近更新 更多