Search code examples
springmongodbspring-bootspring-data-mongodb

Spring use mongo client with aggregation


I have the next code that uses mongo template to run some aggregation:

    AggregationOperation matchStage = match(where(CREATED_BY).is(createdBy)
            .and(APPLICATION).is(appType.toString())
            .and(PATH).regex(pathToFindChildren + ".*"));

    AggregationOperation setStage = context -> new Document("$set",
            new Document("newPath", new Document("$replaceOne",
                    new Document("input", "$path")
                            .append("find", pathToFindChildren)
                            .append("replacement", destinationPathForMove))));

    AggregationOperation projection = Aggregation.project(ID, NAME, PATH, "newPath");

    Aggregation agg = Aggregation.newAggregation(matchStage, setStage, projection);
    AggregationResults<Document> results = mt.aggregate(agg, Folder.class, Document.class);
    return new LinkedList<>(results.getMappedResults());

I want to use the same aggregation but with Mongo client. In other words is there a way to transform the above aggregation to work with following code:

MongoCollection<Document> coll = mc.getDatabase(Database.FOLDER_DB).getCollection(Const.Collection.FOLDER_COLLECTION);
List<Documents> aggAsDocList = agg.toPipeline(<Here I need a AggregationOperationContext>) //here the agg is from the previous code
coll.aggregate(session, aggAsDocList , Document.class); 

from where I can take the AggregationOperationContext?


Solution

  • You can take the AggregationOperationContext from Aggregation.DEFAULT_CONTEXT (https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/Aggregation.html#DEFAULT_CONTEXT).

    Try something like this :

    AggregationOperation matchStage = match(where(CREATED_BY).is(createdBy)
        .and(APPLICATION).is(appType.toString())
        .and(PATH).regex(pathToFindChildren + ".*"));
    
    AggregationOperation setStage = context -> new Document("$set",
        new Document("newPath", new Document("$replaceOne",
                new Document("input", "$path")
                        .append("find", pathToFindChildren)
                        .append("replacement", destinationPathForMove))));
    
    AggregationOperation projection = Aggregation.project(ID, NAME, PATH, "newPath");
    
    Aggregation agg = Aggregation.newAggregation(matchStage, setStage, projection);
    
    MongoCollection<Document> coll = mc.getDatabase(Database.FOLDER_DB).getCollection(Const.Collection.FOLDER_COLLECTION);
    
    List<Document> aggAsDocList = agg.toPipeline(Aggregation.DEFAULT_CONTEXT);
    
    coll.aggregate(session, aggAsDocList, Document.class);