首页 文章

带有nodejs的Monodb - 在计数结果后用组查询

提问于
浏览
2

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

{
    "_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" part,输出nrOfMembers:"312321"

1 回答

  • 1

    你几乎和你的最后一组在一起,你只需要在 _id 前面添加 $ 来表示滑动字段的数量 . $sort管道是另一个问题,因为您尝试排序的字段不存在 . 聚合管道的前提是管道中的一个阶段的结果作为修改后的文档传递给下一个(具有取决于聚合操作的结构),最后一个组管道只生成两个字段 "_id""nrOfMembers" .

    您可以使用 $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) { ... });
    

相关问题