将sql连接查询转换为mongodb

Posted

技术标签:

【中文标题】将sql连接查询转换为mongodb【英文标题】:Convert sql joins query to mongodb 【发布时间】:2019-11-03 13:04:57 【问题描述】:

我在 sql 中有这个查询

select * from SupplyItem si
inner join categories c on si.categories = c._id
inner join suppliers s on si.supplier = s._id
inner join products p on p.supplier = s._id

我在 mongodb 中需要这个查询

我被卡住了

inner join products p on p.supplier = s._id

我当前的查询是

SupplyItem.aggregate([
        $lookup: 
            from: 'categories',
            localField: 'categories',
            foreignField: '_id',
            as: 'categoriess'
        

    , 
    
        $lookup: 
            from: 'suppliers',
            localField: 'supplier',
            foreignField: '_id',
            as: 'suppliers'
        ,

    ,

])

我需要对供应商收集的产品进行计数

【问题讨论】:

对象数据库并不是真的要连接... 任何解决方案??我是 node mongo 的新手 有这个:***.com/questions/37575722/… 【参考方案1】:

你可以试试这个

db.supplyitem.aggregate([
//categories are not required to get count of products by supplier
// $lookup:from:'categories',localField:'categories',foreignField:'_id',as:'categories',
// $unwind:'$categories',
$lookup:from:'suppliers',localField:'supplier',foreignField:'_id',as:'suppliers',
$unwind:'$suppliers',
$lookup:from:'products',localField:'_id',foreignField:'supplier',as:'products',
$unwind:'$products',
//to get count of products
$group:_id:'$suppliers._id',docs:$addToSet:'$products',
$unwind:'$_id',
$project:_id:0,supplier:'$_id',productsCount:$size:'$products'
])

//end result: you will get the supplier id & products count. 
//if you need the supplier name as well (assuming the field is 'name'), you can change the $group as follows
$group:_id:supplier_id:'$suppliers._id',supplier_name:'$suppliers.name',docs:$addToSet:'$products',
$unwind:'$_id',
$project:_id:0,supplier_id:'$_id.supplier_id',supplier_name:'$_id.supplier_name',productsCount:$size:'$products'

【讨论】:

以上是关于将sql连接查询转换为mongodb的主要内容,如果未能解决你的问题,请参考以下文章

将 SQL 连接查询转换为 pyspark 语法

将sql代码转换为linq(内连接查询)

如何将在左连接中具有连接的 sql 转换为查询构建器?

如何将左连接横向 SQL 查询转换为 Laravel Eloquent 查询?

将具有许多连接的复杂 SQL 查询转换为 Eloquent

将包含连接提取的SQL查询转换为Criteria Hibernate查询