我无法在 ProjectionOperation 中的 java mongodb 中执行 map
和 reduce
操作。
我在 native mongo查询
中有项目操作,如下所示:
{
$project: {
data: {
$map: {
input: params.timeArray,
in: {
"key": "$$this",
"value": { "$cond": [{ "$in": ["$$this", "$data.date"] }, "$data", []] }
}
}
}
}
}
我还想在另一个投影操作中进行reduce
操作,如下所示:
{
$project: {
id: 1,
data: { $reduce: { input: "$data", initialValue: [], in: { $concatArrays: ["$$value", "$$this"] } } }
}
}
我已经尝试过这个:
ProjectionOperation projectionOperation1 = Aggregation.project()
.and(VariableOperators.mapItemsOf("data"/*here, I want to pass timeArray*/)
.as("input")
.andApply(context -> new BasicDBObject("value",
ConditionalOperators.when(where("$$this").in("$data.date"))
.then("$data")
.otherwise(new HashSet<>()))))
.as("data");
但它没有给我想要的结果。
我正在使用springboot
版本1.5.10.RELEASE
如有任何帮助,我们将不胜感激!
最佳答案
使用 Spring MongoTemplate
API 运行的投影操作代码:
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
String [] TIME_ARRAY = { "2020-02-20", "2020-02-21", "2020-02-22" }; // values from params.timeArray
Aggregation agg = newAggregation(
project("_id", "data")
.andArrayOf(TIME_ARRAY).as("timeArray")
.andArrayOf().as("emptyArray"),
project()
.and(
Map.itemsOf("timeArray")
.as("element")
.andApply(ctx ->
new Document("key", "$$element")
.append("value",
new Document("$cond",
Arrays.asList(
new Document("$in",
Arrays.asList("$$element", "$data.date")),
"$data",
"$emptyArray")
)
)
)
)
.as("data")
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "collection", Document.class);
results.forEach(doc -> System.out.println(doc.toJson()));
关于java - 如何在Spring Data MongoDB中的ProjectionOperation中投影map和reduce?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60770748/