【问题标题】:Mongoose aggregate: return not _id fieldMongoose 聚合:返回不是 _id 字段
【发布时间】:2016-05-21 03:48:43
【问题描述】:

这些是我的文件:

{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

有可能吗?

【问题讨论】:

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


    【解决方案1】:

    查看$project 运算符,以便稍后在阶段隐藏字段。

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

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

    要包含客户名称,您可以在组运算符中使用$first

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

    【讨论】:

    • 客户名称不是唯一的,所以我想我无法对其进行分组。
    • 啊,好吧-我只是假设由于您问题中的虚拟数据:)
    【解决方案2】:

    你快到了。要获取“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 阶段,但这会导致性能下降。

    【讨论】:

      猜你喜欢
      • 2015-03-25
      • 2015-03-06
      • 2016-08-16
      • 2021-10-04
      • 2021-11-30
      • 2018-07-07
      • 2020-10-10
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多