2013-02-17 77 views
0

我將我的SQL Server數據庫遷移到MongoDB.Now我有一個problerm。如何在MongoDB中實現這個?

select * from AgentStatus a, 
(select Max(TimeStamp) as TimeStamp,ExtNo 
from AgentStatus 
group by Extno) b 
where a.[TimeStamp] = b.[TimeStamp] and b.ExtNo = a.ExtNo 

如果我們使用RMDB,這很簡單,但如何在MongoDB中執行這樣的查詢嗎?或者我必須改變我的架構?而且如何

任何幫助?謝謝!

+0

我試過兩個單在執行內部查詢之後,然後將結果迭代到**查詢整個集合**,其中使用where子句「a。[TimeStamp] = b。[TimeStamp]和b.ExtNo = a.ExtNo」。但是集合有**兩百萬份文件**,雖然我添加了索引,但它仍然非常慢**。 – 2013-02-17 07:26:30

+0

你創建了哪些索引? – WiredPrairie 2013-02-17 11:54:30

+0

(爲什麼要遷移到MongoDB?) – WiredPrairie 2013-02-17 11:55:43

回答

0

您可以使用聚合框架。 假設你有一堆條目:

db.a.find();

{ "_id" : 1, "n" : 1, "d" : ISODate("2012-01-01T00:00:00Z") } 
{ "_id" : 2, "n" : 1, "d" : ISODate("2012-01-12T00:00:00Z") } 
{ "_id" : 3, "n" : 1, "d" : ISODate("2012-02-04T00:00:00Z") } 
{ "_id" : 4, "n" : 2, "d" : ISODate("2012-01-22T00:00:00Z") } 
{ "_id" : 5, "n" : 3, "d" : ISODate("2012-01-07T00:00:00Z") } 
{ "_id" : 6, "n" : 2, "d" : ISODate("2011-12-31T00:00:00Z") } 

你會那麼就組和max:

> db.a.aggregate({$group:{_id:"$n",latest:{$max:"$d"}}}) 

,讓你記錄與該項目的最新時間戳每個n:

> db.a.aggregate({$group:{_id:"$n",latest:{$max:"$d"}}}) 
{ 
    "result" : [ 
      { 
        "_id" : 3, 
        "latest" : ISODate("2012-01-07T00:00:00Z") 
      }, 
      { 
        "_id" : 2, 
        "latest" : ISODate("2012-01-22T00:00:00Z") 
      }, 
      { 
        "_id" : 1, 
        "latest" : ISODate("2012-02-04T00:00:00Z") 
      } 
    ], 
    "ok" : 1 
} 
+0

這是答案[我的最後一個問題](http://stackoverflow.com/questions/14917362/mongodb-aggregation-using-official-c-sharp-driver)?但仍然謝謝!:) – 2013-02-18 01:05:16