MongoDB查询对大于和小于某个值的记录进行分组和计数。

问题描述 投票:0回答:1

能否请您帮忙改正这个查询,将其归类并计算为 洲际 基于 PIB 值大于和小于1.3?

db.collection.aggregate([
  {
    $project:{
      "item":1,
      "PIB":1
    }
  },
  {
    $addFields:{
      moreThan1.3:{
        $cond:[
          {
            $gt:[
              "$PIB",
              1.3
            ]
          },
          1,
          0
        ]
      },
      lessThan1.3:{
        $cond:[
          {
            $lte:[
              "$PIB",
              1.3
            ]
          },
          1,
          0
        ]
      }
    }
  },
  {
    $group:{
      "_id":"$Continente",
      "countSmaller":{
        $sum:"$lessThan1.3"
      },
      "countBigger":{
        $sum:"$moreThan1.3"
      }
    }
  }
]).pretty()

这是Robo 3TMongoDB中的数据库。Database in MongoDB

这个错误出现了。

错误: 第10行: Unexpected number: 第10行: 意外的数字

谢谢您!请您帮助纠正这个查询,将 "Continental "的 "PIB "大于或小于1.3的数据进行分组和统计。

mongodb mongodb-query
1个回答
0
投票

试试这个聚合查询 :

db.collection.aggregate([
  {
    $group: {
      _id: "$continente",
      /** counting docs based on condition, for an on-going doc if condition is met pass in 1 or 0 */
      countSmaller: { $sum: { $cond: [{ $lte: ["$PIB", 1.3] }, 1, 0] } },
      countBigger: { $sum: { $cond: [{ $gt: ["$PIB", 1.3] }, 1, 0] } }
    }
  }
]);

测试: db.getCollection(01MBIG - Actividad 1'.aggregated([ { $...


0
投票

我已经更新了查询,你很接近,我用的是 $addFields 来存储该字段。

db.collection.aggregate([
  {
    $project:{
      "item":1,
      "PIB":1
    }
  },
  {
    $addFields:{
      moreThan10:{
        $cond:[
          {
            $gt:[
              "$PIB",
              10
            ]
          },
          1,
          0
        ]
      },
      lessThan10:{
        $cond:[
          {
            $lte:[
              "$PIB",
              10
            ]
          },
          1,
          0
        ]
      }
    }
  },
  {
    $group:{
      "_id":"$Continente",
      "countSmaller":{
        $sum:"$lessThan10"
      },
      "countBigger":{
        $sum:"$moreThan10"
      }
    }
  }
]).pretty()

希望这能帮到你:)

更新

db.collection.aggregate([
  {
    $project:{
      "item":1,
      "PIB":1
    }
  },
  {
    $addFields:{
      "moreThan1.3":{
        $cond:[
          {
            $gt:[
              "$PIB",
              1.3
            ]
          },
          1,
          0
        ]
      },
      "lessThan1.3":{
        $cond:[
          {
            $lte:[
              "$PIB",
              1.3
            ]
          },
          1,
          0
        ]
      }
    }
  },
  {
    $group:{
      "_id":"$Continente",
      "countSmaller":{
        $sum:"$lessThan1.3"
      },
      "countBigger":{
        $sum:"$moreThan1.3"
      }
    }
  }
]).pretty()
© www.soinside.com 2019 - 2024. All rights reserved.