虽然目前目前不可能使用聚合框架拼接数组(此功能很快将在mongoDB version 3.1.4中提供)但您仍然可以通过followng管道非常接近您想要的内容:
[
{
"$project": {
"article": "$article",
"yymmdd": {
"$dateToString": {
"date": "$published",
"format": "%Y-%m-%d"
}
}
}
},
{
"$unwind": "$article.category"
},
{
"$group": {
"count": {
"$sum": 1
},
"_id": {
"yymmdd": "$yymmdd",
"title": "$article.category.title"
}
}
},
{
"$sort": {
"_id.yymmdd": 1,
"count": -1
}
},
{
"$group": {
"item": {
"$push": {
"count": "$count",
"item": "$_id.title"
}
},
"_id": "$_id.yymmdd"
}
}
]
哪些数据会以下列形式给出结果集:
{u'item': [{u'count': 100, u'item': u'food'}, {u'count': 99, u'item': u'cinema'}, {u'count': 96, u'item': u'tennis'}, {u'count': 92, u'item': u'news'}, {u'count': 91, u'item': u'gossip'}, {u'count': 90, u'item': u'football'}, {u'count': 88, u'item': u'recipes'}, {u'count': 84, u'item': u'tv'}], u'_id': u'2015-05-31'}
{u'item': [{u'count': 96, u'item': u'gossip'}, {u'count': 93, u'item': u'news'}, {u'count': 92, u'item': u'food'}, {u'count': 91, u'item': u'football'}, {u'count': 87, u'item': u'tennis'}, {u'count': 84, u'item': u'recipes'}, {u'count': 84, u'item': u'cinema'}, {u'count': 82, u'item': u'tv'}], u'_id': u'2015-05-29'}
{u'item': [{u'count': 106, u'item': u'cinema'}, {u'count': 104, u'item': u'gossip'}, {u'count': 99, u'item': u'tv'}, {u'count': 98, u'item': u'news'}, {u'count': 96, u'item': u'football'}, {u'count': 94, u'item': u'food'}, {u'count': 93, u'item': u'tennis'}, {u'count': 90, u'item': u'recipes'}], u'_id': u'2015-05-25'}
{u'item': [{u'count': 85, u'item': u'football'}, {u'count': 85, u'item': u'gossip'}, {u'count': 81, u'item': u'cinema'}, {u'count': 80, u'item': u'tennis'}, {u'count': 78, u'item': u'news'}, {u'count': 74, u'item': u'recipes'}, {u'count': 70, u'item': u'food'}, {u'count': 67, u'item': u'tv'}], u'_id': u'2015-05-22'}
每个项目数组按 Headers 出现次数排序 . 然后在应用程序中,您可以将此数组拼接为n以获得前N个计数 . 你可以看看重现它的步骤in this example (in python)