如何在mongodb中合并或分组2已经分组的结果,例如SQL中2 CTE查询的合并?如何从两个查询组中获取累计和?

时间:2019-05-24 07:30:59

标签: mongodb aggregation-framework union-all

我有这样的收藏

[
    {
        "forecast_yy_mm": "18-01",
        "actual_yy_mm": "18-01",
        "value": 1,
    },
    {
        "forecast_yy_mm": "18-01",
        "actual_yy_mm": "18-01",
        "value": 3,
    },
    {
        "forecast_yy_mm": "18-01",
        "actual_yy_mm": "18-02",
        "value": 5,
    },
    {
        "forecast_yy_mm": "18-02",
        "actual_yy_mm": "18-02",
        "value": 7,
    },
    {
        "forecast_yy_mm": "18-02",
        "actual_yy_mm": "18-02",
        "value": 9,
    },
]

使用MongoDB猫鼬,我想按日期分组并获得像这样的结果的累积值。

[
    {
        "yy_mm": "18-01",
        "forecast_cumulative_sum": 9,
        "actual_cumulative_sum": 4
    },
    {
        "yy_mm": "18-02",
        "forecast_cumulative_sum": 16,
        "actual_cumulative_sum": 21
    }
]

我不想在JS部分中使用任何解决方法,因为我试图将其编码为通用代码。

1 个答案:

答案 0 :(得分:0)

尝试如下:

class MyButton: UIButton {
    var isSelectedBinder = BehaviorRelay<Bool>(value: true)
    let disposeBag = DisposeBag()

    override func awakeFromNib() {
        super.awakeFromNib()

        weak var weakSelf = self

        self.rx.tap.subscribe { _ in
            print("TAP")
            guard let strongSelf = weakSelf else { return }
            strongSelf.isSelectedBinder.accept(!strongSelf.isSelectedBinder.value)
            }.disposed(by: self.disposeBag)
    }
}

结果如下:

db.collection.aggregate([
    {
        $facet: {
            "forecast_cumulative_sum":[
                {
                    $group : {
                        _id: "$forecast_yy_mm",
                        "forecast_cumulative_sum": { $sum: "$value"}
                    }           
                }
            ],
            "actual_cumulative_sum":[
                 {
                    $group : {
                        _id: "$actual_yy_mm",
                        "actual_cumulative_sum": { $sum: "$value"}
                    }             
                }
            ],
        }

    }