简体   繁体   English

mongodb总用户按日期计数

[英]mongodb aggregate users count by date

I'm trying to group all users by some date, what I want is name of month and number of users, month will be a variable so it can change to year or week. 我正在尝试按某个日期对所有用户进行分组,我想要的是月份的名称和用户数,月份将是一个变量,因此可以更改为年或周。 Here is my code: 这是我的代码:

logs = user_collection.aggregate([
        # Lets find our records
        {"$match" => {"zip_code" => {"$exists" => true}, "dob" => {"$exists" => true}, "firstname" => {"$exists" => true}, "lastname" => {"$exists" => true}, "email" => {"$exists" => true}}}, 

        # Now lets group on the name counting how many grouped documents we have
        {"$group" => {"date" => { "$#{period_type}" => "$created" }, "count" => {"$sum" => "1" }}} 
      ]) 

period_type in my case is month. 在我的情况下,period_type是month。 Seems like I'm doing something wrong because I have this error 好像我做错了,因为我有这个错误

Mongo::OperationFailure: Database command 'aggregate' failed: (errmsg: 'exception: unknown group operator '$month''; code: '15952'; ok: '0.0').

There are a couple of problems here. 这里有两个问题。 First, the $group operator groups by whatever you specify as the _id , which is missing here. 首先, $group运算符按您指定为_id分组,此处未提供。 Second, all fields (other than _id ) need to follow the <field1>: { <accumulator1> : <expression1> } structure . 其次,所有字段( _id除外)都必须遵循<field1>: { <accumulator1> : <expression1> } 结构

Try substituting your group line for this: 尝试用您的分组电话代替:

{"$group" => {"_id" => { "$#{period_type}" => "$created" }, "count" => {"$sum" => "1" }}}     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM