我有以下查询,我想转换为Mongo然后我怎么能
SELECT COUNT(*)AS count_all,DATE(created_at)AS date_created_at FROM “TABLE”GROUP BY DATE(created_at)
还请解释,以便下次我可以自己做。
答案 0 :(得分:1)
您可以尝试以下操作。我希望这会对你有所帮助。
db."TABLE".group({
"key": {
"created_at": true
},
"initial": {
"count_all": 0
},
"reduce": function(obj, prev) {
if (true != null) if (true instanceof Array) prev.count_all += true.length;
else prev.count_all++;
}
});
答案 1 :(得分:1)
在mongodb中,您可以使用以下聚合管道:
db.collection.aggregate( [
{
$group: {
_id: "$created_at",
count_all: { $sum: 1 }
}
},
{
$project: {
_id: 0, date_created_at: "$_id", count_all: 1
}
}
])
然后可以转换为ruby语法:
project = {"$project" =>
{
"_id" => 0,
"date_created_at" => "$_id",
"count_all" => 1
}
}
group = { "$group" =>
{ "_id" => "$created_at", "count_all" => { "$sum" => 1 } }
}
Table.collection.aggregate([group,project])
有关更多示例,请参阅 docs