社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MongoDB

MongoDB如何筛选在其他集合中找到的记录

GustavoAndrade • 4 年前 • 880 次点击  

在MongoDB中不存在右集合的地方,是否存在与左联接查询等效的查询?

SQL:

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

蒙古数据库: ???

附笔。: 我的初步草图:

db.getCollection('collA').aggregate([
    {
      $lookup:
        {
          from: "collB",
          localField: "_id",
          foreignField: "_id",
          as: "collB"
        }           
   }
   //, {$match : collB is empty}
])
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38271
 
880 次点击  
文章 [ 2 ]  |  最新文章 4 年前
jelongpark
Reply   •   1 楼
jelongpark    5 年前

Neil Lunn的解决方案有效,但我有另一种方法,因为 $lookup pipe不支持“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....

        }
} )
Neil Lunn
Reply   •   2 楼
Neil Lunn    6 年前

你的编辑基本上有答案。简单地 $match 如果数组为空:

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

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