Mongoose聚合:返回不是_id字段

时间:2016-05-20 19:21:33

标签: node.js mongodb mongoose mongodb-query aggregation-framework

这些是我的文件:

{shopId: "aaa", customerId: "bbb", customerName: "xxx", value: 12}  
{shopId: "aaa", customerId: "ccc", customerName: "yyy", value: 12}  
{shopId: "aaa", customerId: "bbb", customerName: "xxx", value: 12}  
{shopId: "ddd", customerId: "bbb", customerName: "xxx", value: 12}  

我想知道给定客户在特定商店花了多少钱。

我知道怎么做:

Docs.aggregate(
    [{ $match: { shopId: selectedShop } },
        {
            $group: {
                    _id: "$customerId",
                    totalVisits: { $sum: 1 },
                    totalValue: { $sum: "$value" }
                }
            }
        ], function (err, result) {
            if (err) {
                //

            } else {
                //

            }
        }
    );  

问题是我得到的结果包含_id: "$customerId"字段,我想获得customerName并隐藏customerId

有可能吗?

2 个答案:

答案 0 :(得分:1)

请查看$project运算符,以便稍后在舞台中隐藏字段。

简而言之:在管道中添加以下内容以隐藏您的客户ID。

{ $project : { _id : 0, totalVisits : 1 , totalValue : 1 } }

要包含您可以在群组运营商中使用$first的客户名称。

如果您想要客户名称并隐藏客户ID,那么为什么不将客户名称分组呢?

答案 1 :(得分:1)

你快到了。获得" customerName"您需要在$first阶段使用$last$group累加器运算符。

a   b   c               
1   100 600             
1   200 500             
1   300 700 





a   b   c   b1  c1  b2  c2
1   100 600 200 500 300 700

当然,如果您不想要Docs.aggregate( [ { $match: { shopId: selectedShop } }, { $group: { "_id": "$customerId", "totalVisits": { $sum: 1 }, "totalValue": { $sum: "$value" }, "customerName": { $first: "$customerName" } }} ], function (err, result) { if (err) { // } else { // } } ); 字段,则可以随时添加$project阶段,但这会导致性能下降。

相关问题