![](/img/trans.png)
[英]Javascript equivalent to LEFT OUTER JOIN with NULL in WHERE clause
[英]MongoDB - Equivalent of LEFT JOIN where one collection isn't exists
在MongoDB中不存在正確集合的情況下,是否有與LEFT JOIN查詢等效的方法?
SQL:
SELECT * FROM TableA as A LEFT JOIN TableB as B ON A.id = B.id
WHERE B.Id IS NULL
MongoDB: ???
PS:我的初始草圖:
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 } } }
])
在數組索引為0
的$exists
測試是查詢中“這是一個包含項目的數組”的最有效方法。
Neil Lunn的解決方案正在工作,但是我有另一種方法,因為$ lookup管道不支持“ from”語句中的Shard收集。
所以我曾經使用如下簡單的Java腳本。 它很容易修改。 但是為了提高性能,您應該有適當的索引!
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.