【问题标题】:Monodb with nodejs - query with group after count resultMongodb with node js - 在计数结果后使用组查询
【发布时间】:2017-05-28 16:20:09
【问题描述】:

我有以下集合,它代表会员去健身房时的刷卡记录。

{
    "_id" : ObjectId(""),
    "content" : {
        "Date_Key" : "",
        "TRANSACTION_EVENT_KEY" : "",
        "SITE_NAME" : "",
        "Swipe_DateTime" : "",
        "Gender" : "",
        "Post_Out_Code" : "",
        "Year_Of_Birth" : "",
        "Time_Key" : "",
        "MemberID_Hash" : "",
        "Member_Key_Hash" : "",
        "Swipes" : ""
    },
    "collection" : "observations"
}

我想返回给定月份中每个健身房滑动次数的成员数量。 例如:

{
   {"nrOfGymSwipes": 0, "nrOfMembers": 10}, // 10 members who swiped 0 times
   {"nrOfGymSwipes": 1, "nrOfMembers": 15}, // 15 members who swiped once
   {"nrOfGymSwipes": 2, "nrOfMembers": 17}, 
   ...
}

我尝试了以下方法:

collection
            .aggregate(
            [{$match: {"content.Swipe_DateTime": {$regex:"201602"}}},
            {$group: {_id: "$content.MemberID_Hash", "nrOfGymSwipes":{$sum: 1}}},
            {$sort: {"nrOfGymSwipes": 1}}],

返回每个成员在给定月份的滑动次数。

.........    
    { _id: '111', nrOfGymSwipes: 16 },
    { _id: '112', nrOfGymSwipes: 16 },
    { _id: '113', nrOfGymSwipes: 17 },
...............

现在我正在考虑按健身房滑动次数进行分组并计算 id,已经尝试过,但它没有返回我的预期

collection
            .aggregate(
            [{$match: {"content.Swipe_DateTime": {$regex:"201602"}}},
            {$group: {_id: "$content.MemberID_Hash", "nrOfGymSwipes":{$sum: 1}}},
            {$group: {_id: "nrOfGymSwipes", "nrOfMembers":{$sum: 1}}}, <---added this
            {$sort: {"nrOfGymSwipes": 1}}],

知道如何解决这个问题吗? 另外,有没有办法改变我获取 json 输出的方式?例如,不显示 _id: "32131" 部分,而是输出 nrOfMembers: "312321"

【问题讨论】:

  • 您在第二组键之前缺少 $

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


【解决方案1】:

您的最后一组已经快到了,您只需在您的 _id 键前面加上 $ 以指示滑动次数字段。 $sort 管道是另一个问题,因为您尝试排序的字段不存在。聚合管道的工作前提是管道中一个阶段的结果作为修改后的文档传递到下一个(根据聚合操作具有自己的结构),最后一个组管道仅生成两个字段,"_id" 和 @ 987654328@.

您可以使用 $project 管道步骤以使 $sort 阶段工作,因为它通过替换以前的 _id 键为您创建 "nrOfGymSwipes" 字段,您可以然后得到所需结构的最终输出。所以你最终的聚合操作应该是:

collection.aggregate([
    { "$match": { "content.Swipe_DateTime": { "$regex":"201602" } } },
    { "$group": { "_id": "$content.MemberID_Hash", "nrOfGymSwipes": { "$sum": 1 } } },
    { "$group": { "_id": "$nrOfGymSwipes", "nrOfMembers": { "$sum": 1 } } }, 
    { "$project": { "_id": 0, "nrOfGymSwipes": "$_id", "nrOfMembers": 1 } },
    { "$sort": { "nrOfGymSwipes": 1 } }
], function (err, result) { ... });

【讨论】:

  • 您的建议现在可以使用了,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 2019-12-17
相关资源
最近更新 更多