【发布时间】:2017-05-02 11:06:07
【问题描述】:
大家好,我在查询数据时遇到了一个大问题。我有这样的文件:
{
"_id" : NumberLong(999789748357864),
"text" : "#asd #weila #asd2 welcome in my house",
"date" : ISODate("2016-12-13T21:44:37.000Z"),
"dateString" : "2016-12-13",
"hashtags" : [
"asd",
"weila",
"asd2"
]
}
我想构建两个查询:
1) 计算每天标签的数量,然后退出,例如:
{_id:"2016-12-13",
hashtags:[
{hashtag:"asd",count:20},
{hashtag:"weila",count:18},
{hashtag:"asd2",count:10},
....
]
}
{_id:"2016-12-14",
hashtags:[
{hashtag:"asd",count:18},
{hashtag:"asd2",count:14},
{hashtag:"weila",count:10},
....
]
}
2)另一个是相同的,但我想设置一个从 2016-12-13 到 2016-12-17 的时间段。
对于第一个查询,我编写了此查询并得到了搜索结果,但在 Spring Data Mongo 中我不知道如何编写。
db.comment.aggregate([
{$unwind:"$hashtags"},
{"$group":{
"_id":{
"date" : "$dateString",
"hashtag": "$hashtags"
},
"count":{"$sum":1}
}
},
{"$group":{
"_id": "$_id.date",
"hashtags": {
"$push": {
"hashtag": "$_id.hashtag",
"count": "$count"
}},
"count": { "$sum": "$count" }
}},
{"$sort": { count: -1}},
{"$unwind": "$hashtags"},
{"$sort": { "count": -1, "hashtags.count": -1}},
{"$group": {
"_id": "$_id",
"hashtags": { "$push": "$hashtags" },
"count": { "$first": "$count" }
}},
{$project:{name:1,hashtags: { $slice: ["$hashtags", 2 ]}}}
]);
【问题讨论】:
标签: mongodb mongodb-query spring-data aggregation-framework spring-data-mongodb