3

The idea is to unite the payment and refund colletions, transform it into a new collection called transaction, which will have the result of this union.

My script

db.payment.aggregate([
    { $replaceRoot: { newRoot: { "_id": "$_id", "type": "payment", "payment": "$$ROOT" } } },
    { $unionWith: { coll: "refund", pipeline: [ { $replaceRoot: { newRoot: { "_id": "$_id", "type": "refund", "refund": "$$ROOT"  } } } ]} }
])

This script is working perfectly

My java code

List<AggregationOperation> list = new ArrayList<>();

    ReplaceRootOperation replecePayment = replaceRoot()
            .withValueOf(
                    ObjectOperators.valueOf("payment").mergeWith(Aggregation.ROOT)
            );

    UnionWithOperation unionWithOperation = UnionWithOperation
            .unionWith("refund")
            .pipeline(
                    replaceRoot().withValueOf(
                            ObjectOperators.valueOf("refund").mergeWith(Aggregation.ROOT)
                    )
            );

    LimitOperation limitOperation = Aggregation.limit(pageSize);

    list.add(replecePayment);
    list.add(unionWithOperation);
    list.add(limitOperation);

    Aggregation aggregation = newAggregation(Transaction.class, list);

    Flux<Transaction> output = mongoTemplate
            .aggregate(aggregation, "payment", Transaction.class);

    Transaction transaction = output.blockFirst();

The object does not return to me as I expect, I believe the problem is ReplaceRootOperation. I didn't find any similar example with what I need for my case, so I implemented it that way for testing purposes only.

My result at the moment

Transaction(id=359fd8a7-2228-40f1-95dc-e52554f5df21, type=null, payment=null, refund=null)
  • I managed to get around the problem by following the guidelines of this other question in the community. https://stackoverflow.com/questions/59697496/how-to-do-a-mongo-aggregation-query-in-spring-data – Waldir Marques Jan 14 '21 at 17:50

0 Answers0