'MongoDB Compass Export Pipeline to Language with other style
In MongoDB Compass, when I choose to export the Aggregation Pipeline to Java, I get something like this:
Arrays.asList(new Document("$group",
new Document("_id", "$loginTime.seconds")
.append("loginTime",
new Document("$min", "$loginTime.seconds"))))
While this seems to be correct, I'd like to know how I can generate the equivalent expression:
List.of(Aggregates.group("$loginTime.seconds", Accumulators.min("loginTime", "$loginTime.seconds)));
Obviously the latter is more straight-forward and declarative enough to understand on first sight. But MongoDB Compass does not offer any option for that. Why.
Solution 1:[1]
I researched a bit based on the comment from @prasad_ It seems that there are related issues on the mongoDB issue tracker see https://jira.mongodb.org/browse/COMPASS-4695
I also think that this would be a very nice feature since longer aggregations are just unreadable and if we need to adapt these we have to re-engineer them quite often.
Have you thought about saving your aggregation stage as a view in the database? Then the pipelines are stored in the mongodb and you can query it like any other collection.
Other than that I thought about exporting the pipeline as js / json / or raw pipeline (I prefer js/json for auto-formatting) and then parse it from a resource folder.
Of course this would mean that you have to somehow come up with a mechanism to replace dynamic parts of the query which could lead to security issues probably, but maybe you can break down parts that are not dynamic.
Aggregation aggregation =
newAggregation(
CustomDocumentAggregationOperation.of(
matchByIdAndOtherValues(objectId, otherValues),
lookupSomeDataOfOtherCollection(),
unwindSomething(),
projectToSomething()));
I adapted this pattern within my repositories so that I can see at a first glance what the aggregation is doing. Hidden behind these static functions is a bunch of bson.Documents and I try to avoid going there...
This is how I assemble multiple Documents to one AggregationOperation
public class CustomDocumentAggregationOperation implements AggregationOperation {
private final Document document;
public CustomDocumentAggregationOperation(Document document) {
this.document = document;
}
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
return aggregationOperationContext.getMappedObject(document);
}
public static AggregationOperation of(Document document) {
return new CustomDocumentAggregationOperation(document);
}
public static List<AggregationOperation> of(@NonNull Document... documents) {
return Arrays.stream(documents)
.map(CustomDocumentAggregationOperation::of)
.collect(Collectors.toList());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Manuel Waltschek |