【问题标题】:Spring Data MongoDB: aggregation framework - sort with nested property throws invalid referenceSpring Data MongoDB:聚合框架 - 使用嵌套属性排序会引发无效引用
【发布时间】:2014-03-10 11:55:59
【问题描述】:

我发现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? 
);

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

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

【问题讨论】:

  • 为我工作。你能显示帖子和评论映射吗?

标签: java spring mongodb spring-data spring-data-mongodb


【解决方案1】:

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

我做了这样的事情:

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

正如我在代码中所写,我只想投影 cmets-Field 以节省一些开销 - 但这确实导致了我的问题!

非常感谢您的提示!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2019-02-28
    • 2020-09-02
    • 2022-08-10
    相关资源
    最近更新 更多