MongoDB聚合查找组大数据速度慢

时间:2020-07-10 07:29:25

标签: mongodb mongoose aggregation-framework aggregate

您好,我是Mongodb的新手,并且聚合查询存在问题。

dbstock.aggregate([
{ 
    $match: {
        "stockLocation": "stockId",
        "companyId": "companyId"
    }
},
{
    $lookup: {
        from: "items",
        let: { item: "$stockItemCode", company: "$companyId" },
        pipeline: [
            { $match:
                { $expr:
                    { $and:
                        [
                            { $eq: [ "$itemCode",  "$$item" ] },
                            { $eq: [ "$companyId", "$$company" ] }
                        ]
                    }
                }
            },
            { $project: { _id: 0, itemName: 1, companyId: 1 } }
        ],
        as: "item"
    }
},
{
    $group: {
        _id: "$stockItemCode",
        itemName: { $last: "$itemName" },
        companyId: { $last: "$companyId" },
        stockLocation: { $last: "$stockLocation" },
        positiveQuantity: { $sum: { $cond: [{ $gt: ['$quantity', 0] }, "$quantity", 0] } },
        negativeQuantity: { $sum: { $cond: [{ $lt: ['$quantity', 0] }, "$quantity", 0] } },
        item: { $last: "$item" }
    }
},
], {
   allowDiskUse: true
})

在没有$ group的情况下查询工作良好,但是当我在查询中使用$ group时,它非常慢,有时需要5到10分钟

0 个答案:

没有答案