在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:???
P.S。:我的初步草图:
db.getCollection('collA').aggregate([
{
$lookup:
{
from: "collB",
localField: "_id",
foreignField: "_id",
as: "collB"
}
}
//, {$match : collB is empty}
])
答案 0 :(得分:1)
你的编辑基本上有答案。只需db.getCollection('collA').aggregate([
{ "$lookup": {
"from": "collB",
"localField": "_id",
"foreignField": "_id",
"as": "collB"
}},
{ "$match": { "collB.0": { "$exists": false } } }
])
数组为空的位置:
0
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open('/var/log/auth.log', 'r')
loglines = follow(logfile)
for line in loglines:
print 'do something here'
数组索引的$exists
测试是在查询中询问的最有效方式“这是一个包含项目的数组”。
答案 1 :(得分:0)
Neil Lunn的解决方案有效,但是我有另一种方法,因为 $ lookup管道在“ from”语句中不支持碎片收集。
所以我以前使用简单的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....
}
} )