簡體   English   中英

Nested class object with Spring data MongoDb aggregation returns null field

[英]Nested class object with Spring data MongoDb aggregation returns null field

我在聚合中包含嵌套的 class 時遇到問題。

這是我收藏中 json 文檔的預覽:

{
    "id": "1234",
    "typeApp": "API",
    "name": "name",
    "versionNum": "1",
    "release": {
        "author": "name",       
        //some other data
    }
}

文檔 java class:

@Document(collection = "myClassExamples")
public class MyClassExampleDocument {
    @Id
    private String id;
    private String typeApp;
    private String name;
    private String versionNum;
    private Release release;
  
    public static class Release {        
        private String author;
        //Other fields...
    }
   }

我正在嘗試構建一個查詢,通過參數中的給定typeApp查找最后一個文檔組,並按versionNum DESC排序以通過typeApp獲取新文檔。

我從一個更簡單的查詢開始,一個簡單的typeApp組:

 Aggregation aggregation = newAggregation(
                Aggregation.sort(Sort.Direction.DESC, "versionNum"),
                Aggregation.group("typeApp"),
                project(MyClassExampleDocument.class)
        )

該查詢返回MyClassExampleDocument列表,其中所有字段都具有 null 值,但使用typeApp填充的id除外。

您知道如何構建聚合以獲取存儲在我的集合中的整個 object 嗎?

謝謝您的幫助 !

您可以使用如下

public List<MyClassExampleDocument> test() {

    Aggregation aggregation = Aggregation.newAggregation(        
        sort(Sort.Direction.DESC, "versionNum"),
        group("typeApp").first("$$ROOT").as("data")
        replaceRoot("data")

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(MyClassExampleDocument.class), MyClassExampleDocument.class).getMappedResults();

}

這是聚合

db.collection.aggregate([
  { "$sort": { versionNum: -1 } },
  {
    "$group": {
      "_id": "$typeApp",
      "data": { "$first": "$$ROOT" }
    }
  },
  { "$replaceRoot": { "newRoot": "$data" } }
])

工作Mongo游樂場

注意:java 代碼未經測試,它是基於工作 mongo 腳本實現的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM