MongoDb 聚合 - 如何获得 $count 和其他属性?

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

MobgoDb 游乐场

尝试 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
3个回答
1
投票

你可以这样做 - 相当于$count

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
    }
  }
])

0
投票

如果你运行

match:"dob.age": 59
输出年龄将是一个常数 59.

在任何情况下,您都需要按年龄运行分组,这样您将获得按年龄排列的总行数:

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

0
投票

因为你没有提到你想依赖 cloud.mongodb.com (cloud mongo),我也想补充一下。 在 cloud mongo 中,您添加以下查询以获取计数:

第一阶段:$匹配:

    /**
     * Query: The query in MQL.
     */
    {
      "YOUR_KEY":"YOUR_VALUE_FOR_FETCH"
    }

第 2 阶段:$count:

/**
 * Provide the field name for the count.
 */
'total'

例子:

云mongo截图:

© www.soinside.com 2019 - 2024. All rights reserved.