我正在尝试按照某个日期对所有用户进行分组,我想要的是月份名称和用户数量,月份将是一个变量,因此可以更改为年份或星期。这是我的代码:
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').
答案 0 :(得分:2)
这里有几个问题。首先,$group
运算符组按照您指定的_id
进行分组,此处缺少。其次,所有字段(_id
除外)都需要遵循<field1>: { <accumulator1> : <expression1> }
structure。
尝试用您的组行代替:
{"$group" => {"_id" => { "$#{period_type}" => "$created" }, "count" => {"$sum" => "1" }}}