简体   繁体   中英

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?

SQL:

SELECT * FROM TableA as A LEFT JOIN TableB as B ON A.id = B.id 
WHERE B.Id IS NULL

MongoDB: ???

PS: My initial sketch:

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:

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".

Neil Lunn's solution is working, but I have another approach, because $lookup pipe does not support Shard collection in the "from" statement.

So I used to use simple java script as follows. 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....

        }
} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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