首页 > 解决方案 > Mongodb 中的日期字段 - 按日期字段分组 ID 年份 - 聚合框架

问题描述

我在处理客户请求时遇到问题。我有以下数据:

{ 
    "_id" : "6489", 
    "post_date" : ISODate("2014-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6490", 
    "post_date" : ISODate("2014-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6491", 
    "post_date" : ISODate("2014-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6492", 
    "post_date" : ISODate("2014-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6493", 
    "post_date" : ISODate("2015-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6494", 
    "post_date" : ISODate("2015-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6495", 
    "post_date" : ISODate("2016-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6496", 
    "post_date" : ISODate("2016-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6497", 
    "post_date" : ISODate("2016-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6498", 
    "post_date" : ISODate("2016-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6499", 
    "post_date" : ISODate("2016-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}
{ 
    "_id" : "6500", 
    "post_date" : ISODate("2017-12-20T17:00:00.000+0000"), 
    "post_modified" : ISODate("2014-06-28T14:33:57.000+0000")
}

我需要输出一个显示年份(posting_date)和帖子数量(_id)的表格。在 SQL 中,这将是计数 _id 和按发布日期(年份)进行的分组。

问题是posting_date 的格式,我必须从中提取年份。格式如下:

 "post_date" : ISODate("0105-08-17T00:00:00.000+0000")

我已经写了一个代码,但它没有工作。这是我的代码:

db.posts.aggregate(
    [
    {
       $project:
         {
           year: { $year: "$post_date" }
         }
     },
        { 
            "$group" : {
                "_id" : {
                    "post_date" : "$post_date"
                }, 
                "COUNT(_id)" : {
                    "$sum" : NumberInt(1)
                }
            }
        }, 
        { 
            "$project" : {
                "_id" : NumberInt(0), 
                "COUNT(_id)" : "$COUNT(_id)", 
                "post_date" : "$_id.post_date"
            }
        }, 
        { 
            "$sort" : {
                "COUNT(_id)" : NumberInt(-1)
            }
        }
    ]
);

有没有人有想法或在我的代码中找到错误?我会很高兴得到帮助。输出应如下所示:

post_date   number of posts
2014    4
2015    2
2016    5
2017    1

非常感谢,吉姆

标签: mongodbmongodb-queryaggregation-framework

解决方案


推荐阅读