简体   繁体   中英

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. 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. Second, all fields (other than _id ) need to follow the <field1>: { <accumulator1> : <expression1> } structure .

Try substituting your group line for this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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