2016-08-23 128 views
3

我試圖在表上執行「group by」,並與另一個表「加入」它。 相應的SQL語句應該是:

SELECT T1.total, T1.email, T1.type, table_2.name FROM 
(SELECT SUM(amount) AS total, email, type 
FROM table_1 
GROUP BY email, type) T1 
INNER JOIN table_2 
on T1.email = table_2.email 

但由於MongoDB中仍然沒有內部連接的功能,我試圖用「$查找」和做任務。這裏是我的代碼:

db.table_1.aggregate([ 
{$group : {_id : {email: "$email", type:"$type"},total: { $sum: "$amount" }}}, 
{$lookup: {from: "table_2", localField: "email", foreignField: "email", as: "details"}} ]); 

但結果我發現了,細節的回報和空對象:

{ "_id" : { "user" : "[email protected]", "type" : "Car" }, "total" : 2, "details" : [ ] } 
{ "_id" : { "user" : "[email protected]", "type" : "Bike" }, "total" : 3, "details" : [ ] } 
{ "_id" : { "user" : "[email protected]", "type" : "Car" }, "total" : 1, "details" : [ ] } 

但是,如果我運行查詢,而無需使用$組,它工作正常。所以我想知道$ group和$ lookup函數是否不能一起使用。如果是的話,是否有解決方法或什麼是完成查詢的最佳方式?

[我使用蒙戈DB版本:> db.version()3.2.7]

回答

10

我找到了解決問題的辦法。我得到空數組的原因是我在$ lookup中使用localField的方式。

因爲我試圖加入table_2與table_1的$組結果,本地字段應該是「_id.email」。

所以工作查詢是:

db.table_1.aggregate([ 
    {$group : {_id : {email: "$email", type:"$type"},total: { $sum: "$amount" }}}, 
    {$lookup: {from: "table_2", localField: "_id.email", foreignField: "email", as: "details"}}, 
    {$match: {details: {$ne: []}}} 
]); 

感謝@Wake和@Clement求助

+0

有道理。我沒有意識到你得到的應該是一個匹配的電子郵件地址空陣列。 – Wake

2

如果你希望你的$查找像一個INNER JOIN工作,那就是,你不不想結果,除非有在查找表中的至少一個匹配的文件,你可以在末尾加上$匹配比較您的查找表的結果爲空數組[]

db.table_1.aggregate([ 
    {$group : {_id : {email: "$email", type:"$type"},total: { $sum: "$amount" }}}, 
    {$lookup: {from: "table_2", localField: "email", foreignField: "email", as: "details"}}, 
    {$match: {details: {$ne: []}}} 
]); 
+0

感謝喚醒。我終於想出了答案。 – KTB

1

從蒙戈VERSI在3.2以後,$ lookup用於支持左外連接。

我想知道$ group和$ lookup函數是不是可以一起使用 。

$ group和$ lookup可以一起使用。

如何使用它INNER JOIN

您有加一個條件篩選結果。使用$匹配。 你也可以試用$ in。

參考

https://www.mongodb.com/blog/post/joins-and-other-aggregation-enhancements-coming-in-mongodb-3-2-part-1-of-3-introduction

http://www.clusterdb.com/mongodb/joins-and-other-aggregation-enhancements-in-mongodb-3-2

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

https://docs.mongodb.com/manual/reference/operator/aggregation/match/

+0

謝謝Clement。我終於想出了答案。 – KTB