Maison  >  Questions et réponses  >  le corps du texte

mongodb - 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 ;

想请问哪位大神能帮忙!谢谢!

PHP中文网PHP中文网2736 Il y a quelques jours483

répondre à tous(3)je répondrai

  • ringa_lee

    ringa_lee2017-04-24 09:15:50

    db.test.aggregate({"$project":{"name":1, "score":1, "totle":1}}, {"$group":{"_id":"$name ", "count":{"$sum":"$score"}}},{"$sort":{"totle":1}},{"$limit":2})
    Je ne sais pas si c'est possible ?

    répondre
    0
  • 高洛峰

    高洛峰2017-04-24 09:15:50

    J'ai bien peur que vous deviez interroger deux fois

    répondre
    0
  • 阿神

    阿神2017-04-24 09:15:50

    Première requête, enregistrez la structure dans une collection temporaire
    La deuxième requête, interrogez la collection temporaire
    La troisième fois - il n'y a pas de troisième fois, supprimez la collection temporaire

    répondre
    0
  • Annulerrépondre