maki
maki

Reputation: 535

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').

Upvotes: 1

Views: 1336

Answers (1)

Jorge Aranda
Jorge Aranda

Reputation: 2080

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" }}}     

Upvotes: 2

Related Questions