Skip to content

Support $expr via criteria query. #4316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-2750-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-2750-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-2750-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>4.1.0-SNAPSHOT</version>
<version>4.1.x-GH-2750-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.aggregation;

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.EvaluationOperators.Expr;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.lang.Nullable;

/**
* A {@link CriteriaDefinition criteria} to use {@code $expr} within a
* {@link org.springframework.data.mongodb.core.query.Query}.
*
* @author Christoph Strobl
* @since 4.1
*/
public class AggregationExpressionCriteria implements CriteriaDefinition {

private final AggregationExpression expression;

AggregationExpressionCriteria(AggregationExpression expression) {
this.expression = expression;
}

/**
* @param expression must not be {@literal null}.
* @return new instance of {@link AggregationExpressionCriteria}.
*/
public static AggregationExpressionCriteria whereExpr(AggregationExpression expression) {
return new AggregationExpressionCriteria(expression);
}

@Override
public Document getCriteriaObject() {

if (expression instanceof Expr expr) {
return new Document(getKey(), expr.get(0));
}
return new Document(getKey(), expression);
}

@Nullable
@Override
public String getKey() {
return "$expr";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@
import org.springframework.data.mapping.context.InvalidPersistentPropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.MongoExpression;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationExpression;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter.NestedDocument;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
Expand Down Expand Up @@ -560,6 +563,13 @@ protected Object convertSimpleOrDocument(Object source, @Nullable MongoPersisten
return exampleMapper.getMappedExample((Example<?>) source, entity);
}

if(source instanceof MongoExpression exr) {
if(source instanceof AggregationExpression age) {
return age.toDocument(new RelaxedTypeBasedAggregationOperationContext(entity.getType(), this.mappingContext, this));
}
return exr.toDocument();
}

if (source instanceof List) {
return delegateConvertToMongoType(source, entity);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
Expand All @@ -37,6 +38,7 @@
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Shape;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.MongoExpression;
import org.springframework.data.mongodb.core.geo.GeoJson;
import org.springframework.data.mongodb.core.geo.Sphere;
import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type;
Expand All @@ -45,7 +47,6 @@
import org.springframework.data.mongodb.util.RegexFlags;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
Expand Down Expand Up @@ -147,6 +148,37 @@ public static Criteria matchingDocumentStructure(MongoJsonSchema schema) {
return new Criteria().andDocumentStructureMatches(schema);
}

/**
* Static factory method to create a {@link Criteria} matching a documents against the given {@link MongoExpression
* expression}.
* <p>
* The {@link MongoExpression expression} can be either something that directly renders to the store native
* representation like
*
* <pre class="code">
* expr(() -> Document.parse("{ $gt : [ '$spent', '$budget'] }")))
* </pre>
*
* or an {@link org.springframework.data.mongodb.core.aggregation.AggregationExpression} which will be subject to
* context (domain type) specific field mapping.
*
* <pre class="code">
* expr(valueOf("amountSpent").greaterThan("budget"))
* </pre>
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Criteria}.
* @since 4.1
*/
public static Criteria expr(MongoExpression expression) {

Assert.notNull(expression, "Expression must not be null");

Criteria criteria = new Criteria();
criteria.criteria.put("$expr", expression);
return criteria;
}

/**
* Static factory method to create a Criteria using the provided key
*
Expand Down Expand Up @@ -1362,7 +1394,7 @@ private Criteria stringBitmask(String operator, String bitmask) {

Assert.hasText(bitmask, "Bitmask must not be null");

target.criteria.put(operator, new Binary(Base64Utils.decodeFromString(bitmask)));
target.criteria.put(operator, new Binary(Base64.getDecoder().decode(bitmask)));
return target;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
import org.springframework.data.mongodb.core.aggregation.StringOperators;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.index.Index;
Expand Down Expand Up @@ -3837,6 +3838,23 @@ public void sliceShouldLimitCollectionValues() {
assertThat(target.values).containsExactly("spring");
}

@Test // GH-2750
void shouldExecuteQueryWithExpression() {

TypeWithFieldAnnotation source1 = new TypeWithFieldAnnotation();
source1.emailAddress = "spring.data@pivotal.com";

TypeWithFieldAnnotation source2 = new TypeWithFieldAnnotation();
source2.emailAddress = "spring.data@vmware.com";

template.insertAll(List.of(source1, source2));

TypeWithFieldAnnotation loaded = template.query(TypeWithFieldAnnotation.class)
.matching(expr(StringOperators.valueOf("emailAddress").regexFind(".*@vmware.com$", "i"))).firstValue();

assertThat(loaded).isEqualTo(source2);
}

private AtomicReference<ImmutableVersioned> createAfterSaveReference() {

AtomicReference<ImmutableVersioned> saved = new AtomicReference<>();
Expand Down Expand Up @@ -4158,6 +4176,7 @@ static class VersionedPerson {
@Field(write = Field.Write.ALWAYS) String lastname;
}

@EqualsAndHashCode
static class TypeWithFieldAnnotation {

@Id ObjectId id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.springframework.data.mongodb.core.convert;

import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
import static org.springframework.data.mongodb.core.aggregation.AggregationExpressionCriteria.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import static org.springframework.data.mongodb.test.util.Assertions.*;
Expand Down Expand Up @@ -43,8 +44,10 @@
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.DocumentTestUtils;
import org.springframework.data.mongodb.core.Person;
import org.springframework.data.mongodb.core.aggregation.ComparisonOperators;
import org.springframework.data.mongodb.core.aggregation.ConditionalOperators;
import org.springframework.data.mongodb.core.aggregation.EvaluationOperators;
import org.springframework.data.mongodb.core.aggregation.EvaluationOperators.Expr;
import org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
Expand Down Expand Up @@ -1461,6 +1464,51 @@ void considersValueConverterWhenPresent() {
assertThat(mappedObject).isEqualTo(new org.bson.Document("text", "eulav"));
}

@Test // GH-2750
void mapsAggregationExpression() {

Query query = query(whereExpr(ComparisonOperators.valueOf("field").greaterThan("budget")));
org.bson.Document mappedObject = mapper.getMappedObject(query.getQueryObject(),
context.getPersistentEntity(CustomizedField.class));
assertThat(mappedObject).isEqualTo("{ $expr : { $gt : [ '$foo', '$budget'] } }");
}

@Test // GH-2750
void unwrapsAggregationExpressionExprObjectWrappedInExpressionCriteria() {

Query query = query(whereExpr(Expr.valueOf(ComparisonOperators.valueOf("field").greaterThan("budget"))));
org.bson.Document mappedObject = mapper.getMappedObject(query.getQueryObject(),
context.getPersistentEntity(CustomizedField.class));
assertThat(mappedObject).isEqualTo("{ $expr : { $gt : [ '$foo', '$budget'] } }");
}

@Test // GH-2750
void mapsMongoExpressionToFieldsIfItsAnAggregationExpression() {

Query query = query(expr(ComparisonOperators.valueOf("field").greaterThan("budget")));
org.bson.Document mappedObject = mapper.getMappedObject(query.getQueryObject(),
context.getPersistentEntity(CustomizedField.class));
assertThat(mappedObject).isEqualTo("{ $expr : { $gt : [ '$foo', '$budget'] } }");
}

@Test // GH-2750
void usageOfMongoExpressionOnCriteriaDoesNotUnwrapAnExprAggregationExpression() {

Query query = query(expr(Expr.valueOf(ComparisonOperators.valueOf("field").greaterThan("budget"))));
org.bson.Document mappedObject = mapper.getMappedObject(query.getQueryObject(),
context.getPersistentEntity(CustomizedField.class));
assertThat(mappedObject).isEqualTo("{ $expr : { $expr : { $gt : [ '$foo', '$budget'] } } }");
}

@Test // GH-2750
void usesMongoExpressionDocumentAsIsIfItIsNotAnAggregationExpression() {

Query query = query(expr(() -> org.bson.Document.parse("{ $gt : [ '$field', '$budget'] }")));
org.bson.Document mappedObject = mapper.getMappedObject(query.getQueryObject(),
context.getPersistentEntity(CustomizedField.class));
assertThat(mappedObject).isEqualTo("{ $expr : { $gt : [ '$field', '$budget'] } }");
}

class WithDeepArrayNesting {

List<WithNestedArray> level0;
Expand Down