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

时间:2018-02-24 10:59:03

标签: mongodb mongo-shell

我正在使用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
 }]
}

提前谢谢

1 个答案:

答案 0 :(得分: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
        }
    ]
}