首頁  >  問答  >  主體

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 天前489

全部回覆(3)我來回復

  • 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":{"$sum":1}},{"$limit":2})
    不知道可行不?

    回覆
    0
  • 高洛峰

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

    恐怕你要分兩次查詢

    回覆
    0
  • 阿神

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

    第一次查詢,將結構保存到一個臨時集合
    第二次查詢,查詢臨時集合
    第三次-沒有第三次,刪除臨時集合

    回覆
    0
  • 取消回覆