use of org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable in project spring-data-mongodb by spring-projects.
the class AggregationTests method letShouldBeAppliedCorrectly.
// DATAMONGO-1538
@Test
@MongoVersion(asOf = "3.2")
public void letShouldBeAppliedCorrectly() {
Sales2 sales1 = Sales2.builder().id("1").price(10).tax(0.5F).applyDiscount(true).build();
Sales2 sales2 = Sales2.builder().id("2").price(10).tax(0.25F).applyDiscount(false).build();
mongoTemplate.insert(Arrays.asList(sales1, sales2), Sales2.class);
ExpressionVariable total = ExpressionVariable.newVariable("total").forExpression(AggregationFunctionExpressions.ADD.of(Fields.field("price"), Fields.field("tax")));
ExpressionVariable discounted = ExpressionVariable.newVariable("discounted").forExpression(ConditionalOperators.Cond.when("applyDiscount").then(0.9D).otherwise(1.0D));
TypedAggregation<Sales2> agg = Aggregation.newAggregation(Sales2.class, Aggregation.project().and(VariableOperators.Let.define(total, discounted).andApply(AggregationFunctionExpressions.MULTIPLY.of(Fields.field("total"), Fields.field("discounted")))).as("finalTotal"));
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
assertThat(result.getMappedResults(), contains(new Document("_id", "1").append("finalTotal", 9.450000000000001D), new Document("_id", "2").append("finalTotal", 10.25D)));
}
use of org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable in project spring-data-mongodb by spring-projects.
the class ProjectionOperationUnitTests method shouldRenderLetExpressionCorrectlyWhenUsingLetOnProjectionBuilder.
// DATAMONGO-1538
@Test
public void shouldRenderLetExpressionCorrectlyWhenUsingLetOnProjectionBuilder() {
ExpressionVariable var1 = newVariable("total").forExpression(AggregationFunctionExpressions.ADD.of(Fields.field("price"), Fields.field("tax")));
ExpressionVariable var2 = newVariable("discounted").forExpression(ConditionalOperators.Cond.when("applyDiscount").then(0.9D).otherwise(1.0D));
Document agg = Aggregation.project().and("foo").let(Arrays.asList(var1, var2), AggregationFunctionExpressions.MULTIPLY.of(Fields.field("total"), Fields.field("discounted"))).as("finalTotal").toDocument(Aggregation.DEFAULT_CONTEXT);
assertThat(agg).isEqualTo(Document.parse(//
"{ $project:{ \"finalTotal\" : { \"$let\": {" + //
"\"vars\": {" + //
"\"total\": { \"$add\": [ \"$price\", \"$tax\" ] }," + //
"\"discounted\": { \"$cond\": { \"if\": \"$applyDiscount\", \"then\": 0.9, \"else\": 1.0 } }" + //
"}," + //
"\"in\": { \"$multiply\": [ \"$$total\", \"$$discounted\" ] }" + "}}}}"));
}
Aggregations