Spring Data MongoDB:聚合框架 - 使用嵌套属性排序会抛出无效引用 [英] Spring Data MongoDB: aggregation framework - sort with nested property throws invalid reference

查看:33
本文介绍了Spring Data MongoDB:聚合框架 - 使用嵌套属性排序会抛出无效引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Spring 论坛中的这篇文章 显然部分讨论了相同的问题,但没有回答我的问题.

I found this article in Spring Forum which obviously dicusses partly the same problem, but has no answer to my question.

给定以下文档...

{
    "_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)...

... I want to do this aggregation (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 -> 抛出无效引用!

... but with Spring -> Throws Invalid Reference!

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 一起使用?

Of course I can do it with the native Java-Driver and without usage of Spring's MongoTemplate but I don't like this approach very much. What can I do to make this exact aggregation work with Spring?

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

推荐答案

发布的代码确实成功了 - 我遇到的问题是别的.

The code as posted indeed works successfully - the problem I had was something else.

我做了这样的事情:

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

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

As I wrote in the code I wanted to project only the comments-Field to save some overhead - but this acutally caused my problem!

非常感谢您的提示!

这篇关于Spring Data MongoDB:聚合框架 - 使用嵌套属性排序会抛出无效引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆