在下面的查询中,我正在添加一个字段(此字段具有ISO日期作为值),然后从该字段中提取小时,然后按小时分组
db.campaigns.aggregate([
{$group : { _id: {$hour:{$add:['$time', 19800000]}}}}
])
Sample record of the collection
db.campaigns.findOne()
{
"_id" : ObjectId("53c7afdab92be74745af9068"),
"time" : ISODate("2013-03-08T12:25:24.973Z"),
"type" : "annoying",
"PINGS" : 143
}
上面的一个在Mongo shell中工作正常,
我正在尝试用Java编写这个查询
这是我的部分Java代码
DBObject group2Fields = new BasicDBObject();
group2Fields.put("hour", new BasicDBObject("$hour", new BasicDBObject("$add",new BasicDBObject("time",19800000))));
DBObject group2 = new BasicDBObject("_id", group2Fields);
DBObject secondGroup = new BasicDBObject("$group", group2);
我收到“errmsg”:“异常:$表达式中不允许包含字段”
答案 0 :(得分:1)
试试这个:
DBObject group2Fields = new BasicDBObject();
BasicDBList addObjects = new BasicDBList();
addObjects.add("$time");
addObjects.add(19800000);
group2Fields.put("$hour", new BasicDBObject("$add", addObjects));
DBObject group2 = new BasicDBObject("_id", group2Fields);
DBObject secondGroup = new BasicDBObject("$group", group2);
答案 1 :(得分:0)
在您的代码中嵌入调用通常可以帮助您实现"可视化"你想要的结构:
BasicDBList addArgs = new BasicDBList();
addArgs.add("$time");
addArgs.add(19800000);
DBObject group = new BasicDBObject("$group",
new BasicDBObject("_id",
new BasicDBObject("$hour",
new BasicDBObject("$add", addArgs)
)
)
);
当然会生成一个group
变量,如下所示进行序列化:
{ "$group" : { "_id" : { "$hour" : { "$add" : [ "$time" , 19800000]}}}}