首页 > mongo如何实现mysql类似的嵌套查询。

mongo如何实现mysql类似的嵌套查询。

目前在做一个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})
不知道可行不?

【热门文章】
【热门文章】