【发布时间】:2016-08-23 03:01:53
【问题描述】:
我正在尝试对一个表执行“分组依据”并将其与另一个表“加入”。 对应的 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版本:> db.version() 3.2.7]
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework