mongodb 按日期汇总用户数

mongodb aggregate users count by date

我正在尝试按某个日期对所有用户进行分组,我想要的是月份名称和用户数量,月份将是一个变量,因此它可以更改为年或周。这是我的代码:

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 在我的例子中是月份。好像我做错了什么因为我有这个错误

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

这里有几个问题。首先,$group 运算符按您指定的 _id 进行分组,这里没有。其次,所有字段(_id除外)都需要遵循<field1>: { <accumulator1> : <expression1> } structure.

尝试用您的群组行代替:

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