MongoDB - 相当于LEFT JOIN,其中一个集合不存在 [英] MongoDB - Equivalent of LEFT JOIN where one collection isn't exists

查看:250
本文介绍了MongoDB - 相当于LEFT JOIN,其中一个集合不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中是否存在权利集合的LEFT JOIN查询等效?

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:我的初始草图:

db.getCollection('collA').aggregate([
    {
      $lookup:
        {
          from: "collB",
          localField: "_id",
          foreignField: "_id",
          as: "collB"
        }           
   }
   //, {$match : collB is empty}
])


推荐答案

你的编辑基本上有答案。只需 $ match 数组为空:

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 } } }
])

$ exists 测试数组索引 0 是在查询中询问的最有效方式这是一个包含项目的数组。

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

这篇关于MongoDB - 相当于LEFT JOIN,其中一个集合不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆