[英]MongoDB - Equivalent of LEFT JOIN where one collection isn't exists
Is there an equivalent to LEFT JOIN query where right collection isn't exists in MongoDB? 在MongoDB中不存在正确集合的情况下,是否有与LEFT JOIN查询等效的方法?
SQL: SQL:
SELECT * FROM TableA as A LEFT JOIN TableB as B ON A.id = B.id
WHERE B.Id IS NULL
MongoDB: ???
MongoDB:
???
PS: My initial sketch: PS:我的初始草图:
db.getCollection('collA').aggregate([
{
$lookup:
{
from: "collB",
localField: "_id",
foreignField: "_id",
as: "collB"
}
}
//, {$match : collB is empty}
])
Well your edit basically has the answer. 好,您的编辑基本上可以找到答案。 Simply
$match
where the array is empty: 只需
$match
,其中数组为空:
db.getCollection('collA').aggregate([
{ "$lookup": {
"from": "collB",
"localField": "_id",
"foreignField": "_id",
"as": "collB"
}},
{ "$match": { "collB.0": { "$exists": false } } }
])
The $exists
test on the array index of 0
is the most efficient way to ask in a query "is this an array with items in it". 在数组索引为
0
的$exists
测试是查询中“这是一个包含项目的数组”的最有效方法。
Neil Lunn's solution is working, but I have another approach, because $lookup pipe does not support Shard collection in the "from" statement. Neil Lunn的解决方案正在工作,但是我有另一种方法,因为$ lookup管道不支持“ from”语句中的Shard收集。
So I used to use simple java script as follows. 所以我曾经使用如下简单的Java脚本。 It's simple and easy to modify.
它很容易修改。 But for performance you should have proper indexes!
但是为了提高性能,您应该有适当的索引!
var mycursor = db.collA.find( {}, {_id: 0, myId:1} )
mycursor.forEach( function (x){
var out = db.collB.count( { yourId : x.myId } )
if ( out > 0) {
print('The id exists! ' + x.myId); //debugging only
//put your other query in here....
}
} )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.