如何将存在的SQL查询转换为MongoDB查询

时间:2020-06-14 09:00:29

标签: sql mongodb mongoose mongodb-query aggregation-framework

我在mongodb上有两个文档,分别是百分比项目。我擅长SQL,可以按如下方式编写PLSql查询,但无法转换为mongodb查询。因为我的mongodb知识水平才刚刚开始。

实际上,我知道必须使用$ gt作为and条件。但是我不知道该怎么说mongodb的不存在或union关键字。如何编写mongodb查询?我应该搜索哪些关键字?

select p.*, "to_top" as list 
  from percentages p
 where p.percentage > 5
   and p.updatetime > sysdate - 1/24
   and not exists (select 1
                     from items i
                    where i.id = p.p_id
                      and i.seller = p.seller)
 order by p.percentage desc
union
select p2.*, "to_bottom" as list 
  from percentages p2
 where p2.percentage > 5
   and p2.updatetime > sysdate - 1/24
   and exists (select 1
                  from items i2
                 where i2.id = p2.p_id
                   and i2.seller = p2.seller)
order by p2.percentage desc

2 个答案:

答案 0 :(得分:1)

MongoDB没有UNION。幸运的是,每个查询都在同一个集合上执行,并且条件非常接近,因此我们可以实现“蒙哥方式”查询。

说明

通常,几乎所有复杂的SQL查询都是通过MongoDB aggregation框架完成的。

  1. 我们按percentage / updatetime过滤文档。 Explanation为什么需要使用$expr
  2. SQL JOIN /子查询是通过$lookup运算符完成的。
  3. MongoDB中的SQL SYSDATE可以是NOWCLUSTER_TIME variable

db.percentages.aggregate([
  {
    $match: {
      percentage: { $gt: 5 },
      $expr: {
        $gt: [
          "$updatetime",
          {
            $subtract: [
              ISODate("2020-06-14T13:00:00Z"), //Change to $$NOW or $$CLUSTER_TIME
              3600000
            ]
          }
        ]
      }
    }
  },
  {
    $lookup: {
      from: "items",
      let: {
        p_id: "$p_id",
        seller: "$seller"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [ "$$p_id", "$id"]
                },
                {
                  $eq: [ "$$seller", "$seller"]
                }
              ]
            }
          }
        },
        {
          $limit: 1
        }
      ],
      as: "items"
    }
  },
  {
    $addFields: {
      list: {
        $cond: [
          {
            $eq: [{$size: "$items"}, 0]
          },
          "$to_top",
          "$to_bottom"
        ]
      },
      items: "$$REMOVE"
    }
  },
  {
    $sort: { percentage: -1 }
  }
])

MongoPlayground

注意::MongoDB聚合具有$facet运算符,该运算符允许对同一集合执行不同的查询。

模式:

db.percentages.aggregate([
  {$facet:{
    q1:[...],
    q2:[...],
  }},
  //We apply "UNION" the result documents for each pipeline into single array
  {$project:{
    data:{$concatArrays:["$q1","$q2"]}
  }},
  //Flatten array into single object
  {$unwind:"$data"}
  //Replace top-level document
  {$replaceWith:"$data"}
])

MongoPlayground

答案 1 :(得分:0)

为什么不将mangoDB数据导入到oracle中并使用sql(这比mango更加容易和强大。)