目前在做一个mongodb的数据分析项目统计分析的功能
说明:
(1)基础统计数据是不定时统计的;
(2)查询展示的周期固定为(小时,天,月,年)等;
(3)相对应的数据要按照对应的字段做以group by对应的字段做 sum,avg 统计。
(4)还要求有分页功能;
以前在mysql中的实现是如下一段sql语句:
--创建表结构
-- CREATE TABLE test(
-- id int PRIMARY KEY auto_increment,
-- name varchar(30),
-- score int
-- );
-- 插入测试数据
-- insert into test (name,score)VALUES('a',1);
-- insert into test (name,score)VALUES('b',2);
-- insert into test (name,score)VALUES('c',3);
-- insert into test (name,score)VALUES('a',2);
-- insert into test (name,score)VALUES('b',3);
-- insert into test (name,score)VALUES('c',1);
具体实现SQL语句:
SELECT * FROM (SELECT name ,sum(score) totle from test GROUP BY name) tem order by totle desc LIMIT 0,2 ;
想请问哪位大神能帮忙!谢谢!
db.test.aggregate({"$project":{"name":1, "score":1, "totle":1}}, {"$group":{"_id":"$name", "count":{"$sum":"$score"}}},{"$sort":{"totle":1}},{"$limit":2})
I don’t know if it’s possible?
I’m afraid you have to query twice
First query, save the structure to a temporary collection
The second query is to query the temporary collection
The third time - there is no third time, delete the temporary collection