我正在尝试在一个表上执行“分组依据”,然后将其“与”另一个表“联接”。相应的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" : "[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的情况下运行查询,则效果很好。所以我想知道$ group和$ lookup函数是否不能一起使用。如果是这样,是否有解决方法,或者完成查询的最佳方法是什么?
[我正在使用的mongo db版本:> db.version()3.2.7]
我找到了问题的答案。我得到空数组的原因是我在$ lookup中使用localField的方式。
由于我正在尝试将table_2与table_1的$ group结果联接在一起,因此本地字段应为“ _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的帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句