【问题标题】:Spring Boot MongoDB Aggregation with ReplaceRoot / How to get the Most Recent Item in a GroupSpring Boot MongoDB 聚合与 ReplaceRoot / 如何获取组中的最新项目
【发布时间】:2018-12-19 16:06:37
【问题描述】:

我想在 Spring Boot 应用程序中获取此 MongoDB 查询的结果。

db.getCollection('contentSource').aggregate( [ { $sort: { "modified": -1 } }, 
{ $group: { _id: "$sourceId", cs: { $push: "$$ROOT" } }}, 
{ $replaceRoot: { newRoot: { $arrayElemAt: ['$cs', 0] } }} ] )

有人知道如何将 replaceRoot 添加到我的聚合中吗?

【问题讨论】:

    标签: spring mongodb aggregation


    【解决方案1】:
        SortOperation sortOperation = new SortOperation(new Sort(Sort.Direction.ASC,"modified"));
    
            GroupOperation groupOperation = group("sourceId").push("$$ROOT").as("cs");
    
            Aggregation aggregation = newAggregation( sortOperation , groupOperation);
    
    AggregationOperation replaceRoot = Aggregation.replaceRoot().withValueOf(ArrayOperators.ArrayElemAt.arrayOf("cs").elementAt(0));
    
            AggregationResults<Document> result = mongoTemplate.aggregate(aggregation,"contentSource", replaceRoot,  Document.class);
    
    
            return result.getMappedResults();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2021-06-15
      • 2013-03-26
      • 1970-01-01
      • 2021-11-03
      • 2020-02-20
      • 2017-07-08
      相关资源
      最近更新 更多