草庐IT

java - 按投影字段分组时引用无效

coder 2023-11-05 原文

我有两个文档:FooQux

Foo 看起来像这样:

{
    "_id": ObjectId("5c52bb1af9b7bb512458a6d1"),
    "name": "Foo 1",
    "description": "This is a Foo",
    "bars": [ 
        {
            "name": "Bar 1",
            "description": "This is a Bar",
            "qux": ObjectId("5c3f3d59d45cca2d1860bb4e")
        },         
        {
            "name": "Bar 2",
            "description": "This is a Bar",
            "qux": ObjectId("5c3f3d59d45cca2d1860bb4e")
        }
    ]
}

Qux 看起来像:

{
    "_id": ObjectId("5c3f3d59d45cca2d1860bb4e"),
    "name": "Qux 1",
    "description": "This is a Qux"
}

我的目标是将相应的Qux嵌入到Foo.bars的每个元素中,如下所示:

[{
    "_id": ObjectId("5c52bb1af9b7bb512458a6d1"),
    "name": "Foo 1",
    "description": "This is a Foo",
    "bars": [ 
        {
            "name": "Bar 1",
            "description": "This is a Bar",
            "qux": {
                "_id": ObjectId("5c3f3d59d45cca2d1860bb4e"),
                "name": "Qux 1",
                "description": "This is a Qux"
             }
        },         
        {
            "name": "Bar 2",
            "description": "This is a Bar document",
            "qux": {
                "_id": ObjectId("5c3f3d59d45cca2d1860bb4e"),
                "name": "Qux 1",
                "description": "This is a Qux"
             }
        }
    ]
}]

我尝试了以下聚合:

Aggregation agg = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("_id").is(id)),
    Aggregation.unwind("bars", true),
    Aggregation.lookup("qux", "bars.qux", "_id", "bars.qux"),
    Aggregation.project("_id", "name", "description")
        .and("bars.qux").arrayElementAt(0).as("bars.qux")
        .and("bars.name").as("bars.name")
        .and("bars.description").as("bars.description"),
    Aggregation.group("_id")
        .push("bars").as("bars")
        .first("name").as("name")
        .first("description").as("description")
);

但由于这一行 .push("bars").as("bars"),它会抛出一个 IllegalArgumentException:

java.lang.IllegalArgumentException: Invalid reference 'bars'!
    at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:100) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:72) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.aggregation.GroupOperation.toDocument(GroupOperation.java:421) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.aggregation.AggregationOperationRenderer.toDocument(AggregationOperationRenderer.java:55) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.aggregation.Aggregation.toPipeline(Aggregation.java:645) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.AggregationUtil.createPipeline(AggregationUtil.java:95) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate.doAggregate(MongoTemplate.java:2070) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate.aggregate(MongoTemplate.java:2046) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.data.mongodb.core.MongoTemplate.aggregate(MongoTemplate.java:1945) ~[spring-data-mongodb-2.1.3.RELEASE.jar:2.1.3.RELEASE]

如果我在没有组操作的情况下执行聚合,它会工作,但我为每个 bar 元素得到一个 Foo 并且每个 Foo 包含一个不同的 bar 元素,这是我在展开它们后所期望的:

[{
    "_id": ObjectId("5c52bb1af9b7bb512458a6d1"),
    "name": "Foo 1",
    "description": "This is a Foo",
    "bars": {
        "name": "Bar 1",
        "description": "This is a Bar",
        "qux": {
            "_id": ObjectId("5c3f3d59d45cca2d1860bb4e"),
            "name": "Qux 1",
            "description": "This is a Qux"
         }
    }
},
{
    "_id": ObjectId("5c52bb1af9b7bb512458a6d1"),
    "name": "Foo 1",
    "description": "This is a Foo",
    "bars": {
        "name": "Bar 2",
        "description": "This is a Bar",
        "qux": {
            "_id": ObjectId("5c3f3d59d45cca2d1860bb4e"),
             "name": "Qux 1",
             "description": "This is a Qux"
        }
    }
}]

有没有办法实现我的目标?

最佳答案

你可以在没有$unwind的情况下得到想要的输出。一旦我们 $lookup 我们就可以 $map qux rom 通过 $indexOfArray$arrayElemAt 连接的数组并合并对象使用 $mergeObjects

db.foo.aggregate([
    {$lookup: {from : "qux", localField : "bars.qux", foreignField : "_id", as : "join"}},
    {$addFields: {bars: {$map : {input : "$bars", as : "b", in : {$mergeObjects :[ "$$b", {qux: {$arrayElemAt : ["$join", {$indexOfArray: ["$join._id", "$$b.qux"]}]}}]}}}}},
    {$project: {join:0}}
]).pretty()

输出

{
        "_id" : ObjectId("5c52bb1af9b7bb512458a6d1"),
        "name" : "Foo 1",
        "description" : "This is a Foo",
        "bars" : [
                {
                        "name" : "Bar 1",
                        "description" : "This is a Bar",
                        "qux" : {
                                "_id" : ObjectId("5c3f3d59d45cca2d1860bb4e"),
                                "name" : "Qux 1",
                                "description" : "This is a Qux"
                        }
                },
                {
                        "name" : "Bar 2",
                        "description" : "This is a Bar",
                        "qux" : {
                                "_id" : ObjectId("5c3f3d59d45cca2d1860bb4e"),
                                "name" : "Qux 1",
                                "description" : "This is a Qux"
                        }
                }
        ]
}

关于java - 按投影字段分组时引用无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467291/

有关java - 按投影字段分组时引用无效的更多相关文章

  1. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  2. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  5. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  6. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  7. ruby - 一个 YAML 对象可以引用另一个吗? - 2

    我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的ruby​​yaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐