KTB*_*KTB 5 mongodb mongodb-query aggregation-framework
我正在尝试在桌面上执行"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
Run Code Online (Sandbox Code Playgroud)
但由于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"}} ]);
Run Code Online (Sandbox Code Playgroud)
但在我得到的结果中,细节返回和空对象:
{ "_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" : [ ] }
Run Code Online (Sandbox Code Playgroud)
但是,如果我在不使用$ group的情况下运行查询,它可以正常工作.所以我想知道$ group和$ lookup函数是否不能一起使用.如果有,那么解决方法或完成查询的最佳方法是什么?
[我正在使用的mongo db版本:> db.version()3.2.7]
KTB*_*KTB 22
我找到了问题的答案.我得到空数组的原因是我在$ 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: []}}}
]);
Run Code Online (Sandbox Code Playgroud)
谢谢@Wake和@Clement的帮助
如果您希望$ 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: []}}}
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18548 次 |
| 最近记录: |