具有来自多个文档的数组对象值之和的MongoDB聚合

时间:2018-11-23 12:35:00

标签: mongodb mongodb-query aggregation-framework

我有一个包含以下数据的集合:

{
    "_id": "1",
    "arrlstdetails": [{
        "_id": "1",
        "quantity": 35.5,
        "units": "m3"
    }]
},{
    "_id": "2",
    "arrlstdetails": [{
            "_id": "1",
            "quantity": 35.5,
            "units": "m3"
        },
        {
            "_id": "2",
            "quantity": 12.25,
            "units": "m3"
        },
        {
            "_id": "3",
            "quantity": 28.20,
            "units": "t"
        }
    ]
}

我想执行MongoDB聚合,以单位(m3或t)进行数量过滤。

这是查询后我想要得到的结果:

示例:1。

{
"Unit":"m3",
"Total quantity sum":"83.25"
}

示例:2。

{
"Unit":"t",
"Total quantity sum":"28.20"
}

如何查询以获取数量总和?

1 个答案:

答案 0 :(得分:4)

使用$unwind$group

// template: <my-custom-form @submit="save"></my-custom-form>
const save = jest.fn()
const wrapper = mount(MyComponent, {methods: { save }, stubs: ['my-custom-form']})
wrapper.find('my-custom-form-stub').trigger('submit')
expect(save).toBeCalled() // Expected mock function to have been called, but it was not called.