mongodb聚合$ group和$ lookup

时间:2016-08-23 03:01:54

标签: mongodb mongodb-query aggregation-framework

我试图通过"执行"组。在桌子上"加入"它与另一张桌子。 相应的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仍然没有内部联接功能,我尝试使用" $ lookup"并完成任务。这是我的代码:

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" : "b@b.com", "type" : "Car" }, "total" : 2, "details" : [ ] }
{ "_id" : { "user" : "a@a.com", "type" : "Bike" }, "total" : 3, "details" : [ ] }
{ "_id" : { "user" : "a@a.com", "type" : "Car" }, "total" : 1, "details" : [ ] }

但是,如果我在不使用$ group的情况下运行查询,它可以正常工作。所以我想知道$ group和$ lookup函数是否不能一起使用。如果有,那么解决方法或完成查询的最佳方式是什么?

[mongo db版本I' m使用:> db.version()3.2.7]

3 个答案:

答案 0 :(得分:20)

我找到了问题的答案。我得到空数组的原因是我在$ lookup中使用了localField。

由于我正在尝试使用table_1的$ group结果加入table_2,因此本地字段应为“_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的帮助

答案 1 :(得分:4)

如果您希望 $ lookup INNER JOIN 一样工作,也就是说,除非至少有一个匹配的文档,否则您不想要结果在查找表中,您可以在最后添加 $ match ,将查找表结果与空数组 [] 进行比较:

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: []}}}
]);

答案 2 :(得分:1)

从Mongo 3.2版开始,$ lookup用于支持左外连接。

  

我想知道是否无法使用$ group和$ lookup函数   在一起。

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

  

如何将其用于INNER JOIN

您还需要添加一个条件来过滤结果。使用$ match。 您也可以尝试使用$ 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/

相关问题