MySQL 查询转换为 MongoDB

MySQL query conversion to MongoDB

我是 MongoDB 的新手。我编写了代码以在 MySQL 中获得报告日期的国家/地区最高死亡值。作为第一步,我试图获取 deaths 列的最大值,但它返回的不是最高值。这是我的 MySQL 代码:

SELECT 
d.country_name, s.dt, MAX(s.deaths)
FROM
Demographics d 
inner JOIN statistics s 
where d.country_id=s.country_id
GROUP BY country_name
ORDER BY MAX(s.deaths) DESC;

正在返回:

Germany 2022-01-29 118335
Bangladesh 2022-01-30 34

要获得相同的结果,与 MongoDB 等效的代码是什么? 为了获得 MongoDB 中死亡列的最大值,我使用了:

db.statistics.aggregate([
  {
    $group: {
      _id: "$country_id",
      maxQuantity: {
        $max: "$deaths"
      }
    }
  }
])

这是我的示例输入:

人口统计

{"country_id":"BGD","country_name":"Bangladesh","population":"164700000","area":"148460","density":"1265"}, {"country_id":"DEU","country_name":"Germany","population":"83200000","area":"357386","density":"232"}

统计数据

{"country_id":"DEU","dt":"2022-01 29", "confirmed_cases":"2016684", "deaths":"118335"},
{"country_id":"DEU","dt":"2022-01-17", "confirmed_cases":"53916", "deaths":"143"}, 
{"country_id":"BGD","dt":"2022-01-30", "confirmed_cases":"12183", "deaths":"34"},
{"country_id":"BGD","dt":"2022-01-29", "confirmed_cases":"10378", "deaths":"21"}, 

已更新:Post 所有者请求每个国家/地区的最大值 deaths

  1. $lookup - 通过 country_id.
  2. 加入 statisticsDemographic collections
  3. $set - 通过转换为整数设置 death 字段。
  4. $sort - 按 death DESC.
  5. 排序
  6. $group - 按 country_id 分组。获取第一个值 ($first),因为结果已在阶段 3 中排序。
  7. $sort - 按 maxQuantity DESC.
  8. 排序
  9. $project - 修饰输出文档。

旁注:将 confirmed_casesdeaths 存储为字符串类型很奇怪。

db.statistics.aggregate([
  {
    "$lookup": {
      "from": "Demographics",
      "localField": "country_id",
      "foreignField": "country_id",
      "as": "demographics"
    }
  },
  {
    "$set": {
      deaths: {
        $toInt: "$deaths"
      }
    }
  },
  {
    $sort: {
      deaths: -1
    }
  },
  {
    $group: {
      _id: {
        country_id: "$country_id"
      },
      country: {
        $first: "$demographics"
      },
      dt: {
        $first: "$dt"
      },
      maxQuantity: {
        $first: "$deaths"
      }
    }
  },
  {
    $sort: {
      maxQuantity: -1
    }
  },
  {
    $project: {
      _id: 0,
      country_name: {
        $first: "$country.country_name"
      },
      dt: "$dt",
      maxQuantity: "$maxQuantity"
    }
  }
])

Sample Mongo Playground


对于 MySQL 查询,INNER JOIN 应该是:

INNER JOIN statistics s ON d.country_id=s.country_id

并且不需要 WHERE