'How to convert MongoDB query or aggregation to a Java object?

Let's say there is a query written in MongoDB native syntax. It could be pretty complex, but somehow it ​is debugged and perfectly polished (see Sample query).

I would like to use the same query in my Spring application (spring-data-mongodb) via ReactiveMongoOperations or whatever.

Commonly in tutorials people suggest using Java builders like this (see General approach). Nevertheless, writing MongoDB queries is itself a struggle, and converting them into another language looks like pain with all kinds of typos, errors and so on that would be grreat to avoid.

I guess it would be natural to have a tool that could simply convert a query into an Aggregation object (from the "like write once, run everywhere" point of view). For example see Desired approach.

Is it possible to reuse native MongoDB queries code (as text) to get result from MongoDB to Java object?


Sample query:

​db.myCollection.aggregate(
                ​[
                  ​{ $match: { status: "A" } },
                  ​{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
                  ​{ $sort: { total: -1 } },
                  ​{ $limit: 2 }
                ​] 
)

General approach:

reactiveMongoOperations.aggregate(
            Aggregation.newAggregation(
                MyCollection.class,
                new MatchOperation(
                    Criteria.where( /* ... */
                ),
                new GroupOperation( /* ... */ )
            ))

Desired approach:

var aggregation = AggregationMagic.parse(
                  MyCollection.class,
             """
                ​[
                  ​{ $match: { status: "A" } },
                  ​{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
                  ​{ $sort: { total: -1 } },
                  ​{ $limit: 2 }
                ​]
             """
)

reactiveMongoOperations.aggregate(aggregation)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source