我在mongodb中有一个带有聚合框架的查询,它返回文档中的主题数。这是通过使用$group操作符完成的,结果如下所示:
{
postsByTopics: [
{
"_id" : "Topic 1",
"count" : 3.0
},
{
"_id" : "Topic 2",
"count" : 1.0
}
]
}
我用投影来获得更好的形状
{
"$project": {
"postsByTopics": {
"$arrayToObject": {
"$map": {
"input": "$postsByTopics",
"as": "el",
"in": {
"k": "$$el._id",
"v": "$$el.count",
}
}
}
},
}
它返回更好的形状结果:
{
postsByTopics: {
"Topic1" : 3.0,
"Topic2" : 1.0
}
}
现在,我想在java spring引导代码中转换这个投影。我找到了project().and(ArrayOperators.ArrayToObject.arrayToObject("postsByTopics"))
和
project().and(VariableOperators.Map.itemsOf("postsByTopics").as("el")
但我正努力把它们结合起来,以达到预期的效果。
发布于 2020-05-09 00:04:09
Spring-用于“复杂”查询的数据语法不友好。
解决方案1:为.andApply
方法实现AggregationExpression
。
ProjectionOperation project = Aggregation.project().and(
ArrayOperators.ArrayToObject.arrayValueOfToObject(
Map
.itemsOf("postsByTopics")
.as("el")
.andApply(agg -> new Document("k", "$$el._id").append("v", "$$el.count"))
)
).as("postsByTopics");
解决方案2:使用MongoDB JSON语法实现AggregationOperation
Aggregation agg = Aggregation.newAggregation(
exp -> new Document("$project",
new Document("postsByTopics",
new Document("$arrayToObject",
new Document("$map",
new Document("input", "$postsByTopics")
.append("as", "el")
.append("in",
new Document("k", "$$el._id")
.append("v", "$$el.count")
)
)
)
)
)
);
发布于 2022-01-25 12:09:04
上面的代码是NoSQL查询,向下与MongoTemplate循环查询几乎相似。也许同样的财产是不同的,希望它能帮助到别人!重要的是将列表保存为投影新属性,我没有用arrayOf(列表)找到解决方案。总是插入列表中的输入:{ elemetnAt:[.他真的错了。
$project {
stats: {
$map: {
input: [ "2018-09-01", "2022-01-24", "2022-01-22", "2018-09-04", "2018-09-05" ],
as: "date",
in: {
$let: {
vars: { dateIndex: { "$indexOfArray": [ "$days.day", "$$date" ] } },
in: {
$cond: {
if: { $ne: [ "$$dateIndex", -1 ] },
then: { $arrayElemAt: [ "$days", "$$dateIndex" ] },
else: { _id: "$$date", date: "$$date", distance: 0 }
}
}
}
}
}
}
project("_id", "days", "category").andArrayOf(timearray).as("daysEmpty"),
project("category").and(
mapItemsOf("daysEmpty")
.as("date")
.andApply(new AggregationExpression() {
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$let",
new Document("vars",
new Document("dateIndex",
new Document("$indexOfArray", asList("$days.day", "$$date"))))
.append("in",
new Document("$cond",
new Document("if",
new Document("$ne", asList("$$dateIndex", -1L)))
.append("then",
new Document("$arrayElemAt", asList("$days", "$$dateIndex")))
.append("else",
new Document("_id", "$$date")
.append("date", "$$date")
.append("distance", 0L)
)
)
)
);
}
})).as("data")
https://stackoverflow.com/questions/61682394
复制相似问题