Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

How do I turn my MongoDB aggregation script into a java spring webflux code for use with mongoTemplete?

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...