【问题标题】:Need to convert this SQL query to MongoDB需要将此 SQL 查询转换为 MongoDB
【发布时间】:2022-01-03 04:06:22
【问题描述】:

我是 MongoDB 的新手。我需要将此 SQL 代码转换为 MongoDB

select TOP 5 r.regionName, COUNT(c.RegionID)
from region as r,
     company as c
where c.RegionID = r._id
group by r.regionName
order by COUNT(c.RegionID) DESC;

【问题讨论】:

  • 也向我们展示您的尝试。
  • 通常尝试一对一翻译是一种不好的方法。通常,在 MongoDB 中,集合的数量比 SQL RDBMS 应用程序中的表数量要少得多。最好尝试用“头脑清醒”来编写 NoSQL 语句

标签: sql mongodb


【解决方案1】:

选项 1。 您可以将聚合框架与 $lookup$group$project$sort$limit 阶段一起使用,但这似乎是一种错误的方法,因为使用 mongoDB 更改关系数据库的真正力量是非规范化和避免连接 ($lookup) 之类的查询。

选项 2。 您将多表关系数据库模式转换为文档模型,然后继续执行简单的 $group$project$sort$limit 阶段聚合查询任务。

由于您没有提供任何 mongodb 文档示例,因此很难提供查询的外观...

【讨论】:

    【解决方案2】:

    尽管有我的评论,我还是尝试提供翻译(未经测试):

    db.region.aggregate([
    {
       $lookup: // left outer join collections
         {
           from: "company",
           localField: "_id",
           foreignField: "RegionID",
           as: "c"
         }
    },
    { $match: { c: { $ne: [] } } }, // remove non-matching documents (i.e. INNER JOIN)
    { $group: { _id: "$regionName", regions: { $addToSet: { "$c.RegionID" } } } }, // group and get distinct regions
    { $project: { regionName: "$_id", count: { $size: "$regions" } , _id: 0} } // some cosmetic and count
    { $sort: { regionName: 1 } }, // order result
    { $limit: 5 } // limit number or returned documents
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多