Mongo 计算按字段值分组的对象数量

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

我有以下 mongo 模型:

{
    "_id" : "5f5a1c1f6976570001783ab7",
    "date" : NumberLong(1590624000),
    "source" : "here",
}

我希望获得按日期分组、源字段位于此处值的文档数量,例如:

{
    "date" : NumberLong(1590624000),
    "count": 5
},

{
    "date" : NumberLong(1590710400),
    "count": 10
}

我应该使用什么 mongo 查询才能得到以下结果?

mongodb mongodb-query aggregation-framework
2个回答
0
投票

使用 $match 过滤您想要的记录,然后使用 $group 按日期分组

在这里测试:游乐场

db.collection.aggregate([
  {
    "$match": {
      "source": "here"
    }
  },
  {
    "$group": {
      "_id": "$date",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "date": "$_id",
      "count": 1
    }
  }
])

0
投票

可以使用聚合查询。

[
{$match:{source:'here'},
{$addFields:{count:1}},
{$group:{_id:'$date'
,totalDocuments:{$sum:"$count"}}
}
]
© www.soinside.com 2019 - 2024. All rights reserved.