Skip to content

DATAMONGO-2153 - Aggregation support for repositories. #743

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>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2153-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>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2153-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 @@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2153-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 @@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.0.DATAMONGO-2153-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference;
import org.springframework.lang.Nullable;

/**
* The context for an {@link AggregationOperation}.
Expand All @@ -33,7 +34,20 @@ public interface AggregationOperationContext {
* @param document will never be {@literal null}.
* @return must not be {@literal null}.
*/
Document getMappedObject(Document document);
default Document getMappedObject(Document document) {
return getMappedObject(document, null);
}

/**
* Returns the mapped {@link Document}, potentially converting the source considering mapping metadata for the given
* type.
*
* @param document will never be {@literal null}.
* @param type can be {@literal null}.
* @return must not be {@literal null}.
* @since 2.2
*/
Document getMappedObject(Document document, @Nullable Class<?> type);

/**
* Returns a {@link FieldReference} for the given field or {@literal null} if the context does not expose the given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference;
import org.springframework.data.mongodb.core.aggregation.Fields.AggregationField;
import org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation.InheritsFieldsAggregationOperation;
import org.springframework.lang.Nullable;

/**
* Rendering support for {@link AggregationOperation} into a {@link List} of {@link org.bson.Document}.
Expand Down Expand Up @@ -75,15 +76,16 @@ static List<Document> toDocument(List<AggregationOperation> operations, Aggregat
* Simple {@link AggregationOperationContext} that just returns {@link FieldReference}s as is.
*
* @author Oliver Gierke
* @author Christoph Strobl
*/
private static class NoOpAggregationOperationContext implements AggregationOperationContext {

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document, java.lang.Class)
*/
@Override
public Document getMappedObject(Document document) {
public Document getMappedObject(Document document, @Nullable Class<?> type) {
return document;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,11 @@ public ExposedFieldsAggregationOperationContext(ExposedFields exposedFields,

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document, java.lang.Class)
*/
@Override
public Document getMappedObject(Document document) {
return rootContext.getMappedObject(document);
public Document getMappedObject(Document document, @Nullable Class<?> type) {
return rootContext.getMappedObject(document, type);
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ public NestedDelegatingExpressionAggregationOperationContext(AggregationOperatio

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document, java.lang.Class)
*/
@Override
public Document getMappedObject(Document document) {
return delegate.getMappedObject(document);
public Document getMappedObject(Document document, Class<?> type) {
return delegate.getMappedObject(document, type);
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference;
import org.springframework.lang.Nullable;

/**
* {@link AggregationOperationContext} implementation prefixing non-command keys on root level with the given prefix.
Expand Down Expand Up @@ -56,11 +57,11 @@ public PrefixingDelegatingAggregationOperationContext(AggregationOperationContex

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document, java.lang.Class)
*/
@Override
public Document getMappedObject(Document document) {
return doPrefix(delegate.getMappedObject(document));
public Document getMappedObject(Document document, @Nullable Class<?> type) {
return doPrefix(delegate.getMappedObject(document, type));
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
Expand Down Expand Up @@ -70,7 +71,16 @@ public TypeBasedAggregationOperationContext(Class<?> type,
*/
@Override
public Document getMappedObject(Document document) {
return mapper.getMappedObject(document, mappingContext.getPersistentEntity(type));
return getMappedObject(document, type);
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document, java.lang.Class)
*/
@Override
public Document getMappedObject(Document document, @Nullable Class<?> type) {
return mapper.getMappedObject(document, type != null ? mappingContext.getPersistentEntity(type) : null);
}

/*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright 2019 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.repository;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;
import org.springframework.data.annotation.QueryAnnotation;

/**
* The {@link Aggregation} annotation can be used to annotate a {@link org.springframework.data.repository.Repository}
* query method so that it runs the {@link Aggregation#pipeline()} on invocation.
* <p />
* Pipeline stages are mapped against the {@link org.springframework.data.repository.Repository} domain type to consider
* {@link org.springframework.data.mongodb.core.mapping.Field field} mappings and may contain simple placeholders
* {@code ?0} as well as {@link org.springframework.expression.spel.standard.SpelExpression SpelExpressions}.
* <p />
* Query method {@link org.springframework.data.domain.Sort} and {@link org.springframework.data.domain.Pageable}
* arguments are applied at the end of the pipeline or can be defined manually as part of it.
*
* @author Christoph Strobl
* @since 2.2
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
@QueryAnnotation
public @interface Aggregation {

/**
* Alias for {@link #pipeline()}. Defines the aggregation pipeline to apply.
*
* @return an empty array by default.
* @see #pipeline()
*/
@AliasFor("pipeline")
String[] value() default {};

/**
* Defines the aggregation pipeline to apply.
*
* <pre class="code">
*
* // aggregation resulting in collection with single value
* &#64;Aggregation("{ '$project': { '_id' : '$lastname' } }")
* List<String> findAllLastnames();
*
* // aggregation with parameter replacement
* &#64;Aggregation("{ '$group': { '_id' : '$lastname', names : { $addToSet : '$?0' } } }")
* List<PersonAggregate> groupByLastnameAnd(String property);
*
* // aggregation with sort in pipeline
* &#64;Aggregation(pipeline = {"{ '$group': { '_id' : '$lastname', names : { $addToSet : '$?0' } } }", "{ '$sort' : { 'lastname' : -1 } }"})
* List<PersonAggregate> groupByLastnameAnd(String property);
*
* // Sort parameter is used for sorting results
* &#64;Aggregation("{ '$group': { '_id' : '$lastname', names : { $addToSet : '$?0' } } }")
* List<PersonAggregate> groupByLastnameAnd(String property, Sort sort);
*
* // Pageable parameter used for sort, skip and limit
* &#64;Aggregation("{ '$group': { '_id' : '$lastname', names : { $addToSet : '$?0' } } }")
* List<PersonAggregate> groupByLastnameAnd(String property, Pageable page);
*
* // Single value result aggregation.
* &#64;Aggregation("{ '$group' : { '_id' : null, 'total' : { $sum: '$age' } } }")
* Long sumAge();
*
* // Single value wrapped in container object
* &#64;Aggregation("{ '$group' : { '_id' : null, 'total' : { $sum: '$age' } } })
* SumAge sumAgeAndReturnAggregationResultWrapperWithConcreteType();
*
* // Raw aggregation result
* &#64;Aggregation("{ '$group' : { '_id' : null, 'total' : { $sum: '$age' } } })
* AggregationResults&lt;org.bson.Document>&gt; sumAgeAndReturnAggregationResultWrapper();
* </pre>
*
* @return an empty array by default.
*/
@AliasFor("value")
String[] pipeline() default {};

/**
* Defines the collation to apply when executing the aggregation.
*
* <pre class="code">
* // Fixed value
* &#64;Aggregation(pipeline = "...", collation = "en_US")
* List<Entry> findAllByFixedCollation();
*
* // Fixed value as Document
* &#64;Aggregation(pipeline = "...", collation = "{ 'locale' : 'en_US' }")
* List<Entry> findAllByFixedJsonCollation();
*
* // Dynamic value as String
* &#64;Aggregation(pipeline = "...", collation = "?0")
* List<Entry> findAllByDynamicCollation(String collation);
*
* // Dynamic value as Document
* &#64;Aggregation(pipeline = "...", collation = "{ 'locale' : ?0 }")
* List<Entry> findAllByDynamicJsonCollation(String collation);
*
* // SpEL expression
* &#64;Aggregation(pipeline = "...", collation = "?#{[0]}")
* List<Entry> findAllByDynamicSpElCollation(String collation);
* </pre>
*
* @return an empty {@link String} by default.
*/
String collation() default "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.springframework.data.mongodb.repository.query;

import org.bson.Document;

import org.springframework.data.mongodb.core.ExecutableFindOperation.ExecutableFind;
import org.springframework.data.mongodb.core.ExecutableFindOperation.FindWithQuery;
import org.springframework.data.mongodb.core.ExecutableFindOperation.TerminatingFind;
Expand All @@ -32,6 +31,7 @@
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.data.repository.query.ResultProcessor;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
Expand Down Expand Up @@ -94,22 +94,36 @@ public Object execute(Object[] parameters) {

ConvertingParameterAccessor accessor = new ConvertingParameterAccessor(operations.getConverter(),
new MongoParametersParameterAccessor(method, parameters));

ResultProcessor processor = method.getResultProcessor().withDynamicProjection(accessor);
Class<?> typeToRead = processor.getReturnedType().getTypeToRead();

return processor.processResult(doExecute(method, processor, accessor, typeToRead));
}

/**
* Execute the {@link RepositoryQuery} of the given method with the parameters provided by the
* {@link ConvertingParameterAccessor accessor}
*
* @param method the {@link MongoQueryMethod} invoked. Never {@literal null}.
* @param processor {@link ResultProcessor} for post procession. Never {@literal null}.
* @param accessor for providing invocation arguments. Never {@literal null}.
* @param typeToRead the desired component target type. Can be {@literal null}.
*/
protected Object doExecute(MongoQueryMethod method, ResultProcessor processor, ConvertingParameterAccessor accessor,
@Nullable Class<?> typeToRead) {

Query query = createQuery(accessor);

applyQueryMetaAttributesWhenPresent(query);
query = applyAnnotatedDefaultSortIfPresent(query);
query = applyAnnotatedCollationIfPresent(query, accessor);

ResultProcessor processor = method.getResultProcessor().withDynamicProjection(accessor);
Class<?> typeToRead = processor.getReturnedType().getTypeToRead();

FindWithQuery<?> find = typeToRead == null //
? executableFind //
: executableFind.as(typeToRead);

MongoQueryExecution execution = getExecution(accessor, find);

return processor.processResult(execution.execute(query));
return getExecution(accessor, find).execute(query);
}

private MongoQueryExecution getExecution(ConvertingParameterAccessor accessor, FindWithQuery<?> operation) {
Expand Down
Loading