【问题标题】:MongoDb Aggregation - How to get $count along with other properties?MongoDb Aggregation - 如何获取 $count 以及其他属性?
【发布时间】:2020-08-18 15:50:34
【问题描述】:

MobgoDb Playground

尝试 1:(仅返回总数)

 db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $count: "total"
  },
  {
    $project: {
      "dob.age": 1,
      "total":1
    }
  }
])

尝试 2(异常 - 管道阶段规范对象必须只包含一个字段)

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $count: "total",
    "dob.age": 1
  } 
])

尝试 3(空对象):

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $group: {
      _id: null,
      total: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      "dob.age": 1
    }
  }
])

【问题讨论】:

标签: node.js mongodb mongodb-query nosql


【解决方案1】:

你可以这样做 - have equivalent to $count

play

db.collection.aggregate([
  {
    $match: { //match condition
      "dob.age": 59
    }
  },
  {
    $group: {//$count equivalent
      _id: null,
      myCount: {
        $sum: 1
      },
      "data": {//all other fields
        $push: "$$ROOT"
      }
    }
  },
  {
    $project: {//removing null id - you can skip this if null id is not a problem
      _id: 0
    }
  }
])

【讨论】:

  • 1) $$ROOT 是什么? 2) 如果我只想要一个属性和 Total,这会不会对性能不利,因为我将在管道中传递所有不需要的属性?
  • 你可以这样做。从文档中查找 $first, $addToSet, $last, $push 和更多内容。在高层次上,"fieldOne": { $push: "$fieldOne"} 每个运营商都有自己的价值。您可以使用$push
【解决方案2】:

如果您运行match:"dob.age": 59,则输出年龄将是一个常数 59。

在任何情况下,您都需要运行 group by,这样您就可以按年龄获得总行数:

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $group: {
      _id: "$dob.age",
      total: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      age: "$_id",
      "total": 1
    }
  }
])

否则我建议简单地运行:

db.collection.count({"dob.age": 59}) // it will be 2 as well

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 2012-05-06
    • 2019-06-22
    • 1970-01-01
    • 2016-12-23
    • 2012-10-16
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多