Mongo DB在多个阵列上的聚合

时间:2017-03-17 14:21:01

标签: mongodb aggregation-framework

我想从我的购物车项目和未删除的捆绑包中检索。 我的购物车看起来像这样:

{
 "_id": "589474849d7b3f439797faf1",
 "bundles": [{
    "id": "57c98e25298cd0f908021c12",
    "serial": "xxxx",
    "status": ""
 }],
 "items": [{
    "id": "589de9a690d632ccbc10cd64",
    "status": "deleted",
    "quantity": 1,
    "serial": "fffff"
 }]
}

我尝试的是:

[
            {$match: condition},
            {$unwind: {"path": "$items", "preserveNullAndEmptyArrays": true}},
            {$unwind: {"path": "$bundles", "preserveNullAndEmptyArrays": true}},
            {$match: {"items.status": {$ne: "deleted"}}},
            {$match: {"bundles.status": {$ne: "deleted"}}},
            {
                "$group": {
                    "_id": "$_id",
                    currency: {$first: "$currency"},
                    tenant: {$first: "$tenant"},
                    user: {$first: "$user"},
                    "items": {"$addToSet": "$items"},
                    "bundles": {"$addToSet": "$bundles"}
                }
            }
        ];

它适用于所有情况,除非只有一个已删除的项目和多个包。查询根本不返回任何包

预期产出:

{
"_id": "589474849d7b3f439797faf8",

"items": [{
    "id": "589de9a690d632ccbc10cd64",
    "quantity": 1,
    "serial": "fff"

}, {
    "id": "589de9a690d632ccbc10c55",
    "quantity": 1,
    "serial": "xxx"
}],
"bundles": [{
    "id": "57c98e25298cd0f908021c12",
    "serial": "pppp"
}]
}

1 个答案:

答案 0 :(得分:0)

哦,谢谢大家,我找到了解决方案,过滤器就可以了解

[{
$match: "condition"
}, {
$project: {
    items: {
        $filter: {
            input: "$items",
            as: "item",
            cond: {
                $ne: ["$$item.status", "deleted"]
            }
        }
    },
    bundles: {
        $filter: {
            input: "$bundles",
            as: "bundle",
            cond: {
                $ne: ["$$bundle.status", "deleted"]
            }
        }
    }

}
}]