Spring 使用 mongo 客户端进行聚合

问题描述 投票:0回答:1

我有下一个使用 mongo 模板来运行一些聚合的代码:

    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());

我想使用相同的聚合,但使用 Mongo 客户端。换句话说,有没有办法将上述聚合转换为与以下代码一起使用:

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); 

我可以从哪里获取 AggregationOperationContext?

spring mongodb spring-boot spring-data-mongodb
1个回答
0
投票

你可以这样尝试:

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);
© www.soinside.com 2019 - 2024. All rights reserved.