【问题标题】:How do I add values from both of result in MongoDB?如何在 MongoDB 中添加两个结果中的值?
【发布时间】:2021-04-15 16:26:00
【问题描述】:

这是我从以下两个查询中得到的两个结果。

查询一个

db.game.aggregate( [ 
{ $group : { _id : "$HomeTeam", shots: { $sum : "$HS" } } },
{ $sort : { shots : -1 } }
])

查询一个结果

{ "_id" : "Man City", "shots" : 386 }
{ "_id" : "Liverpool", "shots" : 335 }
{ "_id" : "Chelsea", "shots" : 325 }
{ "_id" : "Tottenham", "shots" : 308 }
{ "_id" : "Leicester", "shots" : 298 }
{ "_id" : "Crystal Palace", "shots" : 294 }
{ "_id" : "Man United", "shots" : 284 }
{ "_id" : "Everton", "shots" : 279 }
{ "_id" : "Fulham", "shots" : 274 }
{ "_id" : "Wolves", "shots" : 267 }
{ "_id" : "Newcastle", "shots" : 266 }
{ "_id" : "Southampton", "shots" : 258 }
{ "_id" : "Arsenal", "shots" : 256 }
{ "_id" : "West Ham", "shots" : 245 }
{ "_id" : "Cardiff", "shots" : 230 }
{ "_id" : "Bournemouth", "shots" : 229 }
{ "_id" : "Watford", "shots" : 224 }
{ "_id" : "Burnley", "shots" : 210 }
{ "_id" : "Huddersfield", "shots" : 203 }
{ "_id" : "Brighton", "shots" : 200 }

查询二

db.game.aggregate( [ 
{ $group : { _id : "$AwayTeam", shots: { $sum : "$AS" } } },
{ $sort : { shots : -1 } }
])

查询两个结果

{ "_id" : "Man City", "shots" : 297 }
{ "_id" : "Chelsea", "shots" : 281 }
{ "_id" : "Man United", "shots" : 242 }
{ "_id" : "Liverpool", "shots" : 239 }
{ "_id" : "Tottenham", "shots" : 228 }
{ "_id" : "Southampton", "shots" : 222 }
{ "_id" : "Bournemouth", "shots" : 218 }
{ "_id" : "Leicester", "shots" : 217 }
{ "_id" : "Everton", "shots" : 216 }
{ "_id" : "Watford", "shots" : 210 }
{ "_id" : "Arsenal", "shots" : 210 }
{ "_id" : "Wolves", "shots" : 207 }
{ "_id" : "Huddersfield", "shots" : 197 }
{ "_id" : "Crystal Palace", "shots" : 197 }
{ "_id" : "West Ham", "shots" : 196 }
{ "_id" : "Cardiff", "shots" : 187 }
{ "_id" : "Fulham", "shots" : 179 }
{ "_id" : "Newcastle", "shots" : 178 }
{ "_id" : "Brighton", "shots" : 165 }
{ "_id" : "Burnley", "shots" : 149 }

那么我如何进行查询,将两个镜头相加。像这样将相同的球队投篮加起来的事情。

{ "_id" : "Man City", "Totalshots" : 683 }

【问题讨论】:

标签: javascript database mongodb nosql relational-database


【解决方案1】:
  • $facetHSAS 两个字段的结果分开
  • $project 使用 $concatArrays 将两个数组合并到一个数组中
  • $unwind解构result数组
  • $group _idshots
  • $sort shots 按降序排列
db.game.aggregate([
  {
    $facet: {
      HS: [
        {
          $group: {
            _id: "$HomeTeam",
            shots: { $sum: "$HS" }
          }
        }
      ],
      AS: [
        {
          $group: {
            _id: "$AwayTeam",
            shots: { $sum: "$AS" }
          }
        }
      ]
    }
  },
  { $project: { result: { $concatArrays: ["$AS", "$HS"] } } },
  { $unwind: "$result" },
  {
    $group: {
      _id: "$result._id",
      Totalshots: { $sum: "$result.shots" }
    }
  },
  { $sort: { Totalshots: -1 } }
])

Playground

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 2023-01-14
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2022-09-28
    相关资源
    最近更新 更多