带nodejs的Monodb – 计数结果后用组查询

当有会员去健身房的时候,我有以下这个代表滑动logging的集合。

{ "_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”

你几乎在那里与你的最后一个组,你只需要在你的_id键前添加$以指示滑动次数字段。 $sortpipe道是另一个问题,因为你试图sorting的字段不存在。 集合pipe道工作的前提是pipe道中的一个阶段的结果作为修改后的文档传递到下一个阶段(根据集合操作自己的结构),最后一个集合pipe道只产生两个字段"_id""nrOfMembers"

您可以使用$projectpipe道步骤来使$sort阶段工作,因为它通过replace之前的_id键为您创build"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) { ... });