gpt4 book ai didi

java - Spring数据MongoDB : How do I represent $eq in project aggregation query?

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:59 24 4
gpt4 key购买 nike

我正在尝试将此 javascript 代码转换为 java 代码以在 Spring Data 中使用:

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 中工作?

最佳答案

这就是我解决它的方法,它可能不是最有效的方法,但它似乎不需要太多代码重写就可以工作。

首先,我查看了这个帖子中的答案: Aggregation Project Group By extracted day, month and year with Spring Data

布莱克七建议我使用一个特殊的自定义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"]}}}

关于java - Spring数据MongoDB : How do I represent $eq in project aggregation query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com