按 2 个字段在 MongoDB 中聚合(分组依据)查询

Aggregate (group by) query in MongoDB by 2 fields

我正在使用 MongoDB。我的集合对象结构如下:

{
"_id" : ObjectId("5a58800acebcda57188bf0aa"),
"title" : "Article title",
"categories" : "politics",
"url" : "https://example.com",
"article_date" : ISODate("2018-01-11T10:00:00.000Z"),
"content" : "content here..."
},
{
"_id" : ObjectId("5a58800acebcda57188bf0aa"),
"title" : "Article title 2",
"categories" : "economics",
"url" : "https://example.com",
"article_date" : ISODate("2018-01-12T10:00:00.000Z"),
"content" : "content here..."
}

文章每天都在发布,我有很多类别。 如何按日期对数据进行分组并按特定类别对文档进行计数,例如:

{
 "date": ISODate("2018-01-11T10:00:00.000Z"),
 "result": [{
     "category": "politics",
     "count": 2
  }, {
    "category": "economics",
    "count": 1
 }]
},
{
 "date": ISODate("2018-01-12T10:00:00.000Z"),
 "result": [{
     "category": "politics",
     "count": 2
  }, {
    "category": "economics",
    "count": 1
 }]
}

提前致谢

您需要 $group 两次才能得到结果,首先 article_datecategories 然后 $group article_date

db.art.aggregate([
    {$group : {
        _id : {article_date : "$article_date", categories : "$categories"},
        count : {$sum : 1}
    }},
    {$group : {
        _id : {article_date : "$_id.article_date"},
        result : {$push : {category : "$_id.categories", count : "$count"}}
    }},
    {$addFields :{
        _id : "$_id.article_date"
    }}
]).pretty()

相关示例数据的结果

{
    "_id" : ISODate("2018-01-11T10:00:00Z"),
    "result" : [
        {
            "category" : "politics",
            "count" : 1
        }
    ]
}
{
    "_id" : ISODate("2018-01-12T10:00:00Z"),
    "result" : [
        {
            "category" : "economics",
            "count" : 1
        }
    ]
}