简体   繁体   English

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

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

相关问题 Javascript 等效于 LEFT OUTER JOIN 在 WHERE 子句中为 NULL - Javascript equivalent to LEFT OUTER JOIN with NULL in WHERE clause 如何在 Mongodb 和 NodeJS 中通过 _id 和 where 条件加入两个集合 - How to JOIN two collection by _id with where condition in Mongodb and NodeJS ZCCADCDEDB567ABAE643E15DCF0974E503Z 相当于 JOIN ... WHERE - Mongoose equivalent of JOIN … WHERE 集合未保存在mongodb中(猫鼬填充文档中的故事集合) - Collection isn't being saved in mongodb (Story collection from the mongoose populate documentation) MongoDB 查找字段不存在的所有文档,如果存在则应用字段运算符 ($max) 条件 - MongoDB find all docs where field doesn't exists, plus if exists apply field operator ($max) condition 如何在没有标签的地方添加标签? - How to add a tag where there isn't one yet? Mongoose/MongoDB 创建集合(如果不存在则基于架构) - Mongoose/MongoDB Create Collection if not exists based on Schema dropCollection不会删除集合 - dropCollection isn't dropping the collection FeathersJs LEFT 加入另一个表(MongoDb) - FeathersJs LEFT join another table (MongoDb) 我的JavaScript图片库滑块的右滑块不起作用,而我的左滑块是 - My JavaScript image gallery slider's right slider isn't working and my left one is
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM