是否有与 LEFT JOIN 查询等效的查询,其中 MongoDB 中不存在右集合?
SQL:
SELECT * FROM TableA as A LEFT JOIN TableB as B ON A.id = B.id
WHERE B.Id IS NULL
MongoDB:???
P.S.:我的最初草图:
db.getCollection('collA').aggregate([
{
$lookup:
{
from: "collB",
localField: "_id",
foreignField: "_id",
as: "collB"
}
}
//, {$match : collB is empty}
])
最佳答案
好吧,您的编辑基本上已经有了答案。只需$match
,其中数组为空:
db.getCollection('collA').aggregate([
{ "$lookup": {
"from": "collB",
"localField": "_id",
"foreignField": "_id",
"as": "collB"
}},
{ "$match": { "collB.0": { "$exists": false } } }
])
$exists
对 0
数组索引进行测试是在查询中询问“这是一个包含项目的数组吗”的最有效方法。
关于javascript - MongoDB - 相当于 LEFT JOIN,其中一个集合不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398842/