【发布时间】: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