2017-07-10 50 views
0

的工會:如何查詢的MongoDB像我有resloved這個問題SQL

db.coll1.aggregate([ 
    { 
     $match:{ 
      $or:[ 
       {time:{$lt:145941000},code:413} 
       ,{time:{$lt:145942000},code:415} 
      ] 
     } 
    } 
    ,{ $sort:{time:-1}} 
    ,{ $group:{_id:"$code" 
      ,lastMatch:{$first:"$price"} 
     } 
    } 
]) 

這是下面的集合:

collection

我想這樣的查詢:

SELECT code, price FROM table1 WHERE code = 1 AND time<123xxx ORDER BY time desc LIMIT 1 
UNION 
SELECT code, price FROM table1 WHERE code = 2 AND time<24xxx ORDER BY time desc LIMIT 1 
UNION 
SELECT code, price FROM table1 WHERE code = 3 AND time<1xxx ORDER BY time desc LIMIT 1 
UNION 
... 

何我可以像這樣查詢mongodb嗎? 我知道如何查詢之一,但它似乎是MongoDB中的總不能夠「聯盟」

db.m20170705.aggregate([ 
    { 
     $match:{code:1 
      ,time:{$lte:145940500} 
     } 
    } 
    ,{$sort:{time:-1}} 
    ,{$limit:1} 
]) 
union ???? 
+0

你到目前爲止試過了什麼? –

+0

幾乎重複的:https://stackoverflow.com/questions/4715820/how-to-order-by-with-union –

回答

0

不知道MongoDB的(但我們知道,SQL),我會說ORDER BY不是SELECT S IN A的一部分UNION,因此必須在末尾放置一次

SELECT code, price FROM table1 WHERE code = 1 AND time<123xxx 
UNION 
SELECT code, price FROM table1 WHERE code = 2 AND time<24xxx 
UNION 
SELECT code, price FROM table1 WHERE code = 3 AND time<1xxx 
UNION 
... 
ORDER BY time desc 

LIMIT作品不同在這種情況下,它必須以其他方式實現,例如子查詢中,如果有的話MongoDB中)