我试图将此javascript代码转换为要在Spring Data中使用的java代码:
proj3={"$project": {
"comms" : 1,
"same" : { "$eq" : ["$comms.i" , "$max"]},
"max" : 1,
"_id" : 1
}
};
我似乎无法弄明白。
我试过这个:
BasicDBObject o3 = new BasicDBObject();
o3.append("$eq", "[\"$comms.i\",\"$max\"]");
Aggregation aggCount2 = newAggregation(project("comms", "max", "_id").andExpression("same", o3));
logger.info(aggCount2.toString());
这是记录的内容:
{ "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1}}
我也读过这个帖子:Spring Data MongoDB - $eq within $project support但是海报似乎已经放弃并使用了executeCommand选项,而不是我想去的路线。
如何让这段代码在java Spring Data Mongodb中运行?
答案 0 :(得分:0)
这就是我解决它的方法,它可能不是最有效的方法,但似乎没有太多的代码重写就可以工作。
首先,我看了这个帖子的答案: Aggregation Project Group By extracted day, month and year with Spring Data
Blakes Seven建议我使用一个特殊的自定义aggregationOperation类,以便聚合代码将采用BasicDBObjects:
public class CustomGroupOperation implements AggregationOperation {
private DBObject operation;
public CustomGroupOperation (DBObject operation) {
this.operation = operation;
}
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}
接下来,您只需将所需的项目代码格式化为BasicDBObject:
BasicDBList basicDBList = new BasicDBList();
basicDBList.add("$comms.i");
basicDBList.add("$max");
Aggregation aggCount2 = newAggregation(
match(),
project(),
group(),
new CustomGroupOperation(new BasicDBObject("$project",
new BasicDBObject("comms", 1)
.append("max", 1)
.append("_id", 1)
.append("same", new BasicDBObject("$eq", basicDBList)))),
match(),
project(),
group(),
sort());
在记录器中打印出来,您会看到javascript代码的格式现在正确无误。
{ "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1 , "same" : { "$eq" : [ "$comms.i" , "$max"]}}}