mongoose聚合:返回不_id字段

这些是我的文件:

{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} 

我想知道给定客户在选定的店铺中花了多less钱。

我知道该怎么做:

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

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

可能吗?

看看$ project操作符,以便在后面的阶段中隐藏字段。

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

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

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

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

你几乎在那里。 要获得“customerName”,您需要在$group阶段使用$first$last累加器操作符。

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

当然,如果你不需要_id字段,你总是可以添加一个$project阶段,但是会导致性能下降。