MongoDB - Equivalent of LEFT JOIN where one collection isn't exists

后端 未结 2 1360
南旧
南旧 2020-12-10 19:58

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         


        
2条回答
  •  抹茶落季
    2020-12-10 20:27

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

提交回复
热议问题