Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot MongoDB Aggregation with ReplaceRoot / How to get the Most Recent Item in a Group

I want to get the result of this MongoDB query in a Spring Boot Application.

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

Does anyone know how to add the replaceRoot to my Aggregation?

like image 465
vklein Avatar asked Dec 19 '18 16:12

vklein


1 Answers

    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();
like image 166
Oto-obong Eshiett Avatar answered Nov 03 '22 20:11

Oto-obong Eshiett