gpt4 book ai didi

java - Spring 数据 MongoDB : aggregation framework - sort with nested property throws invalid reference

转载 作者:可可西里 更新时间:2023-11-01 10:31:48 25 4
gpt4 key购买 nike

我找到了 this article in Spring Forum这显然部分讨论了相同的问题,但没有回答我的问题。

给定以下文档...

{
"_id": { "$oid": "5214b5d529ee12460939e2ba"},
"title": "this is my title",
"tags": [ "fun", "sport" ],
"comments": [
{
"author": "alex",
"text": "this is cool",
"createdAt": 1
},
{
"author": "sam",
"text": "this is bad",
"createdAt": 2
},
{
"author": "jenny",
"text": "this is bad",
"createdAt": 3
}
]
}

...我想做这个聚合(Javascript)...

//This is as concise as possible to focus on the actual problem which is the sort operation when ported to Spring!  
db.articles.aggregate(
{$unwind:"$comments"},
//do more like match, group, etc...
{$sort:{"comments.createdAt":-1}} //Sort descending -> here the problem occurs in Spring (works in Javascript!)
);

...但是使用 Spring -> 抛出无效引用!

Aggregation agg = newAggregation(
unwind("comments"),
sort(Direction.DESC, "comments.createdAt") //Throws invalid reference 'comments.createdAt'!
//How can I make this work?
);

当然,我可以使用 native Java 驱动程序而不使用 Spring 的 MongoTemplate 来完成它,但我不太喜欢这种方法。我该怎么做才能使这种精确聚合与 Spring 一起工作?

我使用的是当前版本 1.4.0.RELEASE。

最佳答案

发布的代码确实可以成功运行 - 我遇到的问题是其他问题。

我做了这样的事情:

Aggregation agg = newAggregation(
project("comments"), //This was the problem! Without this it works as desired!
unwind("comments"),
sort(Direction.DESC, "comments.createdAt")
);

正如我在代码中所写的那样,我只想投影评论 - 字段以节省一些开销 - 但这实际上导致了我的问题!

非常感谢您的提示!

关于java - Spring 数据 MongoDB : aggregation framework - sort with nested property throws invalid reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22299411/

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