繁体   English   中英

MongoDB-等同于不存在一个集合的LEFT JOIN

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM