首页 > 解决方案 > 如何使用聚合查询在 mongodb 中获取计数?

问题描述

我试图使用聚合查询来获取数据库的计数。

我的情景

使用权

[{
    "id": 1,
    name: 'laptop'
}, {
    "id": 2,
    name: 'deasktop'
}]

询问

db.access.aggregate([
    {
        $match: {}
    },
    {
        $group: {
            total: { $sum: 1 }
        }
    }
])

执行查询
我得到了输出

[{
    "total": 2
}]

异常输出

{
    total: 1
    result: [{
        "id": 1,
        name: 'laptop'
    }, {
        "id": 2,
        name: 'deasktop'
    }]
}

如何使用聚合查询获取此输出。

标签: mongodbmongodb-queryaggregation-framework

解决方案


你需要$push你的文件在$group阶段

db.access.aggregate([
  {
    $match: {}
  },
  {
    $group: {
      _id: null,
      result: {
        $push: "$$ROOT"
      },
      total: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

Mongo游乐场

链接 $$ROOT


推荐阅读