我想在一张表上执行"group by"操作,并与另一张表进行"join"操作。 相应的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"}} ]);
但是在我得到的结果中,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 函数。如果是这样,是否有解决方法或者完成查询的最佳方式是什么?
[我使用的 MongoDB 版本:> db.version() 3.2.7]