我想查询数据库,以便找到每秒发送到图表中以显示活动趋势的帖子数。我使用spring-data-mongo但是现在,第一步是在mongo shell中执行此操作,然后再担心如何使用java。
我在其上使用了聚合框架,如下所示:
db.post.group({
key:{dateCreated: 1},
cond: { dateCreated:
{
"$gt": new ISODate("2013-08-09T05:51:15Z"),
"$lt": new ISODate("2013-08-09T05:51:20Z")
}
},
reduce: function(cur, result){
result.count += 1
},
initial: {count:0}
})
结果令人鼓舞,但似乎是因为ISODate的小数部分,计数似乎是错误的,因为它每秒进行分组,每次计数为1。
[
{
"dateCreated" : ISODate("2013-08-09T05:51:15.332Z"),
"count" : 1
},
{
"dateCreated" : ISODate("2013-08-09T05:51:15.378Z"),
"count" : 1
},
{
"dateCreated" : ISODate("2013-08-09T05:51:15.377Z"),
"count" : 1
},
// many more here
]
有没有办法只考虑秒部分,如下所示:
[
{
"dateCreated" : ISODate("2013-08-09T05:51:15Z"),
"count" : 5
},
{
"dateCreated" : ISODate("2013-08-09T05:51:16Z"),
"count" : 8
},
{
"dateCreated" : ISODate("2013-08-09T05:51:17Z"),
"count" : 3
},
{
"dateCreated" : ISODate("2013-08-09T05:51:18Z"),
"count" : 10
},
{
"dateCreated" : ISODate("2013-08-09T05:51:19Z"),
"count" : 2
},
{
"dateCreated" : ISODate("2013-08-09T05:51:20Z"),
"count" : 13
}
]
感谢您阅读此内容。
答案 0 :(得分:1)
对于那些处于相同情况的人。这是我如何修改我的查询。感谢@Sammaye。
db.post.aggregate(
{
$match: { dateCreated:
{
"$gt": new ISODate("2013-08-09T05:51:15.000Z"),
"$lt": new ISODate("2013-08-09T05:51:20.000Z")
}
}
},
{
$group: {
_id: {
hour: {$hour: "$dateCreated"},
minute: {$minute: "$dateCreated"},
second: {$second: "$dateCreated"}
},
cnt: {$sum : 1}
}
}
)
{
"result" : [
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 19
},
"cnt" : 26
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 18
},
"cnt" : 29
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 17
},
"cnt" : 27
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 16
},
"cnt" : 25
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 15
},
"cnt" : 16
}
],
"ok" : 1
}