【问题标题】:How write get sum of array with mapReduce MongoDB?如何使用 mapReduce MongoDB 编写获取数组的总和?
【发布时间】:2020-11-13 23:52:17
【问题描述】:

给定以下数据库架构:

{
    '_id': 5079,
    'name': 'Lincoln County', 
    'state': 'AR',
     'population': 13024,
    'cases': [{'date': '2020-03-16', 'count': 1}, {'date': '2020-03-22', 'count': 1}, 
              {'date': '2020-03-24', 'count': 1}, {'date': '2020-03-26', 'count': 2}], 
    'deaths': [{'date': '2020-03-27', 'count': 1}, {'date': '2020-04-02', 'count': 1}, 
               {'date': '2020-05-28', 'count': 2}, {'date': '2020-05-30', 'count': 1}] 
}

MongoDB mapReduce 函数会生成每个州的 covid19 病例总数的集合。为每个州生成一个记录,其中包含 2 个字母的缩写和 covid 病例总数?

【问题讨论】:

  • 请提供您尝试实现结果的代码,它将让社区更好地帮助您。

标签: mongodb mongodb-query


【解决方案1】:

试试这个查询:

db.collection.aggregate([
  {
    "$project": {
      "total": {
        "$sum": {
          "$map": {
            "input": "$cases",
            "as": "c",
            "in": "$$c.count"
          }
        }
      },
      "state": 1
    }
  }
])

例如here

查询使用$map 创建一个数组,其中包含来自cases.count 和$sum 这些值的值。
此外,字段输出为count,其中包含$sum 和使用state: 1 的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 2019-10-16
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多