我一直在努力编写将 mongo shell 命令转换为 java mongo 驱动程序之上的 java 查询,以便在我的 webapp 项目中调用它:命令如下:
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}
}
}
)
上面的查询在 mongo shell 中输出以下格式:
{
"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
}
我使用 java mongo driver 在 java 中编写相同的查询失败。以下是我的查询:
DBObject matchStart = new BasicDBObject("$match",new BasicDBObject("dateCreated",new BasicDBObject("$gt",startTime).append("$lt",endTime)));
DBObject field = new BasicDBObject("dateCreated",1);
field.put("h", new BasicDBObject("$hour","$dateCreated"));
field.put("m", new BasicDBObject("$minute","$dateCreated"));
field.put("s", new BasicDBObject("$second","$dateCreated"));
DBObject project = new BasicDBObject("$project",field);
DBObject groupField = new BasicDBObject("_id","$s");
groupField.put("count", new BasicDBObject("$sum",1));
DBObject group = new BasicDBObject("$group",groupField);
AggregationOutput output = mongoOperations.getCollection("post").aggregate(matchStart,project,group);
return output;
它返回下面的结果集:
{"result" : [
{ "_id" : 19 , "count" : 26} ,
{ "_id" : 18 , "count" : 29} ,
{ "_id" : 17 , "count" : 27} ,
{ "_id" : 16 , "count" : 25} ,
{ "_id" : 15 , "count" : 16}
] ,
"ok" : 1.0}
我在查询包括分钟部分和小时部分时遇到了挑战。如何调整我的查询以输出与 mongo shell 中相同的结果集。
谢谢你看那个