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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…