Compare commits

..

76 Commits

Author SHA1 Message Date
Mark Paluch
83307c424f DATAMONGO-2454 - Release version 3.0 M2 (Neumann). 2020-01-17 09:39:03 +01:00
Mark Paluch
8394523645 DATAMONGO-2454 - Prepare 3.0 M2 (Neumann). 2020-01-17 09:38:43 +01:00
Mark Paluch
62be436569 DATAMONGO-2454 - Updated changelog. 2020-01-17 09:38:37 +01:00
Mark Paluch
44e6f5fa3f DATAMONGO-2383 - After release cleanups. 2020-01-16 16:11:55 +01:00
Mark Paluch
f2fb05662f DATAMONGO-2383 - Prepare next development iteration. 2020-01-16 16:11:54 +01:00
Mark Paluch
a1fbe31551 DATAMONGO-2383 - Release version 3.0 M1 (Neumann). 2020-01-16 16:05:23 +01:00
Mark Paluch
fca1a79f81 DATAMONGO-2383 - Prepare 3.0 M1 (Neumann). 2020-01-16 16:05:03 +01:00
Mark Paluch
cbf87e6e49 DATAMONGO-2383 - Updated changelog. 2020-01-16 16:04:59 +01:00
Mark Paluch
af133c26d0 DATAMONGO-2432 - Updated changelog. 2020-01-15 12:51:13 +01:00
Christoph Strobl
ab5b1f0140 DATAMONGO-2451 - Fix value conversion for id properties used in sort expression.
Previously we falsely converted the sort value (1/-1) into the id types target value when a Field annotation had been present.

Original pull request: #822.
2020-01-15 11:51:42 +01:00
Mark Paluch
3a5876537b DATAMONGO-2431 - Updated changelog. 2020-01-15 10:36:36 +01:00
Mark Paluch
48f51d0fb0 DATAMONGO-2450 - Polishing.
Replace stream with for-loop.

Original pull request: #820.
2020-01-15 10:15:14 +01:00
Christoph Strobl
fb499f8c69 DATAMONGO-2450 - Apply array filters to bulk write.
Original pull request: #820.
2020-01-15 10:15:06 +01:00
Mark Paluch
bcc2c94e03 DATAMONGO-2440 - Polishing.
Replace SpringJUnit4ClassRunner with SpringRunner.

Original pull request: #821.
2020-01-15 09:30:12 +01:00
Mark Paluch
284f547e99 DATAMONGO-2437 - Polishing.
Mention changes in Aggregation _id handling in what's new. Reformat code.

Original pull request: #821.
2020-01-15 09:30:09 +01:00
Christoph Strobl
d824f3b8b2 DATAMONGO-2437 - Fix complex id handling when reading aggregation results.
Removed Unwrapping complex id values.
Template.aggregate now behaves like aggregateStream or its reactive counterpart.

Original pull request: #821.
2020-01-15 09:30:07 +01:00
Christoph Strobl
7b1a96f4a9 DATAMONGO-2448 - Bump version to 3.0 SNAPSHOT.
In preparation for the upcoming breaking changes when switching to the MongoDB Java Driver 4.0 and the breaking changes required for that update (expected for Milestone 2), we eagerly bump the version number to 3.0.

Original pull request: #819.
2020-01-13 14:29:09 +01:00
Christoph Strobl
4f75fec5c5 DATAMONGO-2447 - Upgrade MongoDB Drivers to 3.12.0 (sync) and 1.13.0 (reactive). 2020-01-10 11:22:49 +01:00
Mark Paluch
61bd56dd74 DATAMONGO-2442 - Polishing.
Reduce visibility of test methods for JUnit 5 tests.

Original pull request: #818.
2020-01-08 15:12:47 +01:00
Christoph Strobl
b4222c5646 DATAMONGO-2442 - Polishing.
Transition touched test classes to JUnit Jupiter.

Original pull request: #818.
2020-01-08 15:12:44 +01:00
Christoph Strobl
4a45928aee DATAMONGO-2442 - Fix thenValueOf in $cond builder.
We now create a field reference when calling the builder instead of using the value as is.

Original pull request: #818.
2020-01-08 15:12:23 +01:00
Mark Paluch
e2200eccf7 DATAMONGO-2440 - Polishing.
Iterate over List instead of using the Stream API.

Reduce visibility of JUnit 5 test methods. Consolidate assertions.

Original pull request: #817.
2020-01-08 15:01:57 +01:00
Christoph Strobl
96c4901e7f DATAMONGO-2440 - Fix field target type conversion for collection values.
We now preserve the collection nature of the source type when applying custom target type conversions. Prior to this change collection values had been changed to single element causing query errors in MongoDB when using $in queries.

Original pull request: #817.
2020-01-08 15:01:44 +01:00
Christoph Strobl
1393f23f3b DATAMONGO-2423 - Polishing.
Update nullability annotations and reduce visibility in tests.

Original pull request: #815.
2020-01-08 13:24:10 +01:00
Christoph Strobl
9bbe1f2a26 DATAMONGO-2423 - Nullability refinements for Update.
Ease non null restrictions for operators that may use null values like $set.

Original pull request: #815.
2020-01-08 13:23:53 +01:00
Mark Paluch
eacfe2b8f7 DATAMONGO-2444 - Update copyright years to 2020. 2020-01-07 08:59:27 +01:00
Jens Schauder
674f0cca2b DATAMONGO-2422 - Updated changelog. 2019-12-04 14:32:45 +01:00
Jens Schauder
da7b51a51e DATAMONGO-2421 - Updated changelog. 2019-12-04 12:09:46 +01:00
Mark Paluch
a1b5175299 DATAMONGO-2430 - Upgrade to mongo-java-driver 3.11.2. 2019-12-04 11:43:07 +01:00
Mark Paluch
56fff286aa DATAMONGO-2418 - Polishing.
Reformat code.

Original pull request: #814.
2019-12-04 10:32:04 +01:00
Christoph Strobl
60112b4d14 DATAMONGO-2418 - Obtain EvaluationContextExtensions lazily when parsing Bson queries.
An eager evaluation of the context extension can lead to errors when e.g. the security context was not present.

Original pull request: #814.
2019-12-04 10:32:04 +01:00
Mark Paluch
277b7a1c7c DATAMONGO-2410 - Polishing.
Simplify cast. Extend test with DBObject interface.

Original pull request: #813.
2019-12-04 08:56:43 +01:00
Christoph Strobl
c5b892f03b DATAMONGO-2410 - Fix Document to BasicDBObject conversion.
Original pull request: #813.
2019-12-04 08:56:35 +01:00
Mark Paluch
dbf43941be DATAMONGO-765 - Polishing.
Reformat code. Update ticket references.

Original pull request: #806.
2019-11-26 15:21:29 +01:00
Denis Zavedeev
1d98b77f3d DATAMONGO-765 - Support skip and limit parameters in GridFsTemplate and ReactiveGridFsTemplate.
Leverage `skip` and `limit` methods exposed in `GridFSFindIterable` to support limiting and skipping results.
In particular these changes allow the `find(Query)` method to correctly consider parameters of a page request.

Original pull request: #806.
2019-11-26 15:21:04 +01:00
Mark Paluch
cd4e4065ff DATAMONGO-2370 - Polishing.
Align since version to 2.3 until we have an indication for a major version bump. Tweak docs.

Original pull request: #803.
2019-11-20 10:12:34 +01:00
Christoph Strobl
9f4872de4f DATAMONGO-2370 - Polishing.
Use JUnit Jupiter api for tests of touched classes and fix parsing errors in disabled ones.

Original pull request: #803.
2019-11-20 10:12:30 +01:00
Christoph Strobl
7abf69e575 DATAMONGO-2370 - Add support for $round aggregation operator.
Original pull request: #803.
2019-11-20 10:12:27 +01:00
Mark Paluch
588ed2b0e2 DATAMONGO-2402 - Updated changelog. 2019-11-18 12:43:26 +01:00
Mark Paluch
8a228f22cd DATAMONGO-2401 - Updated changelog. 2019-11-18 12:16:26 +01:00
Christoph Strobl
d652b2bdb4 DATAMONGO-2414 - Introduce MongoServerCondition to replace JUnit 4 TestRules.
MongoServerCondition replaces the JUnit 4 TestRules (MongoVersionRule & ReplicaSet) with a JUnit Jupiter ExecutionCondition.

Original Pull Request: #807
2019-11-14 11:10:20 +01:00
Mark Paluch
f7e527e45c DATAMONGO-2414 - Polishing.
Use longer timeout to cater for slower CI environments.

Original Pull Request: #807
2019-11-14 11:09:58 +01:00
Mark Paluch
aede7c9cad DATAMONGO-2414 - Guard drain loop in AsyncInputStreamHandler with state switch.
We now use a non-blocking state switch to determine whether to invoke drainLoop(…) from Subscriber completion.

Previously, we relied on same thread identification assuming if the subscription thread and the completion thread were the same, that we're already running inside the drain loop.
It turns out that a I/O thread could also run in event-loop mode where subscription and completion happens on the same thread but in between there's some processing and so the the call to completion is a delayed signal and not being called on the same stack as drainLoop(…).
The same-thread assumption was in place to avoid StackOverflow caused by infinite recursions.

We now use a state lock to enter the drain loop. Any concurrent attempts to re-enter the drain loop in Subscriber completion is now prevented to make sure that we continue draining while not causing stack recursions.

Original Pull Request: #807
2019-11-14 11:09:19 +01:00
Mark Paluch
1a5de2e1db DATAMONGO-2331 - Polishing.
Remove deprecated methods accepting Update in favor of methods accepting UpdateDefinition in Template APIs.
Hide AggregationUpdate constructor.

Tweak Javadoc and reference documentation.

Original pull request: #789.
2019-11-13 09:51:46 +01:00
Christoph Strobl
cc07a1bbb4 DATAMONGO-2331 - Guard test execution.
Original pull request: #789.
2019-11-13 09:51:39 +01:00
Christoph Strobl
32cbae0e5f DATAMONGO-2331 - Add support for Update with an aggregation pipeline.
Now the update methods exposed by (Reactive)MongoOperations also accept an Aggregation Pipeline via AggregationUpdate.

The update can consist of the following stages:

* AggregationUpdate.set(...).toValue(...) -> $set : { ... }
* AggregationUpdate.unset(...) -> $unset : [ ... ]
* AggregationUpdate.replaceWith(...) -> $replaceWith : { ... }

AggregationUpdate update = Aggregation.newUpdate()
    .set("average").toValue(ArithmeticOperators.valueOf("tests").avg())
    .set("grade").toValue(ConditionalOperators.switchCases(
        when(valueOf("average").greaterThanEqualToValue(90)).then("A"),
        when(valueOf("average").greaterThanEqualToValue(80)).then("B"),
        when(valueOf("average").greaterThanEqualToValue(70)).then("C"),
        when(valueOf("average").greaterThanEqualToValue(60)).then("D"))
        .defaultTo("F")
    );

template.update(Student.class)
    .apply(update)
    .all();

Original pull request: #789.
2019-11-13 09:51:22 +01:00
Mark Paluch
9eaf67148d DATAMONGO-2385 - Polishing.
Remove null checks for arguments known to be not-null. Remove Nullable annotations from methods that never return null.

Original pull request: #802.
2019-11-11 14:17:01 +01:00
Christoph Strobl
ff60149166 DATAMONGO-2385 - Remove unnecessary null checks in MongoConverters.
Original pull request: #802.
2019-11-11 14:10:00 +01:00
Mark Paluch
f7a010827d DATAMONGO-2409 - Polishing.
Adapt also ExecutableFindOperation.DistinctWithProjection.asType() to return the appropriate TerminatingDistinct.

Original pull request: #805.
2019-11-11 10:22:27 +01:00
Christoph Strobl
1e8c4cec5b DATAMONGO-2409 - Fix return type of Kotlin extension function for ReactiveFindOperation.DistinctWithProjection.asType().
Original pull request: #805.
2019-11-11 10:22:22 +01:00
Mark Paluch
0e0b45597b DATAMONGO-2403 - Polishing.
Use handle(…) to skip values instead of flatMap(…) to reduce overhead.

Original pull request: #804.
2019-11-08 13:51:41 +01:00
Christoph Strobl
b014fe4c7c DATAMONGO-2403 - Fix aggregation simple type result retrieval from empty document.
Projections used within an aggregation pipeline can result in empty documents emitted by the driver. We now guarded those cases and skip those documents within a Flux or simply return an empty Mono depending on the methods signature.

Original pull request: #804.
2019-11-08 13:47:56 +01:00
Christoph Strobl
ead7679f21 DATAMONGO-2382 - Updated changelog. 2019-11-04 15:39:54 +01:00
Christoph Strobl
18cf94dc34 DATAMONGO-2381 - Updated changelog. 2019-11-04 10:34:50 +01:00
Christoph Strobl
30d99445e2 DATAMONGO-2393 - Remove capturing lambdas and extract methods.
Original Pull Request: #799
2019-10-31 12:50:33 +01:00
Mark Paluch
839aecee84 DATAMONGO-2393 - Support configurable chunk size.
We now allow consuming GridFS files using a configurable chunk size. The default chunk size is now 256kb.

Original Pull Request: #799
2019-10-31 12:50:09 +01:00
Mark Paluch
c6592b01b0 DATAMONGO-2393 - Polishing.
Extract read requests into inner class.

Original Pull Request: #799
2019-10-31 12:49:45 +01:00
Mark Paluch
48176a833c DATAMONGO-2393 - Fix BufferOverflow in GridFS upload.
AsyncInputStreamAdapter now properly splits and buffers incoming DataBuffers according the read requests of AsyncInputStream.read(…) calls.
Previously, the adapter used the input buffer size to be used as the output buffer size. A larger DataBuffer than the transfer buffer handed in through read(…) caused a BufferOverflow.

Original Pull Request: #799
2019-10-31 12:49:18 +01:00
Mark Paluch
0facdcfa98 DATAMONGO-2393 - Use drain loop for same-thread processing in GridFS download stream.
We now rely on an outer drain-loop when GridFS reads complete on the same thread instead of using recursive subscriptions to avoid StackOverflow. Previously, we recursively invoked subscriptions that lead to an increased stack size.

Original Pull Request: #799
2019-10-31 12:48:55 +01:00
Christoph Strobl
837a9885f2 DATAMONGO-2399 - Upgrade to MongoDB Java Driver 3.11.1 2019-10-30 10:47:47 +01:00
Mark Paluch
6cc5bc627a DATAMONGO-2388 - Polishing.
Use StringJoiner to create comma-delimited String. Add nullability annotations.

Original pull request: #797.
2019-10-28 10:58:17 +01:00
Christoph Strobl
84f7f433f7 DATAMONGO-2388 - Fix CodecConfigurationException when reading index info that contains DbRef.
Provide the default CodecRegistry when converting partial index data to its String representation used in IndexInfo.

Original pull request: #797.
2019-10-28 10:47:22 +01:00
Mark Paluch
7df9e932f7 DATAMONGO-2390 - Polishing.
Reformat code.

Original pull request: #800.
2019-10-28 10:10:26 +01:00
Christoph Strobl
5308e6c37f DATAMONGO-2390 - Polishing.
Switch touched test files to JUnit Jupiter.

Original pull request: #800.
2019-10-28 10:07:16 +01:00
Christoph Strobl
bc1c6c9a64 DATAMONGO-2390 - Add support for maxTimeMS to AggregationOptions.
maxTimeMs defines the time limit for the aggregation operations. If not specified or set to zero, operations will not time out.

Original pull request: #800.
2019-10-28 10:07:08 +01:00
Mark Paluch
62006129ca DATAMONGO-2394 - Polishing.
Reformat code.

Original pull request: #798.
2019-10-28 09:31:53 +01:00
Christoph Strobl
5c2370399f DATAMONGO-2394 - Polishing.
Move tests to JUnit Jupiter.

Original pull request: #798.
2019-10-28 09:31:52 +01:00
Christoph Strobl
3bffe402c0 DATAMONGO-2394 - Fix test issues related to JUnit5 upgrade.
Execution time and test order changed by using JUnit5. This commit fixes some of the issues related to index creation where actually not needed.

Original pull request: #798.
2019-10-28 09:31:50 +01:00
Christoph Strobl
6959c56df6 DATAMONGO-2394 - Fix distance conversion for derived finder using near along with GeoJSON.
GeoJson requries the distance to be in meters instead of radians, so we now make sure to convert it correctly

Original pull request: #798.
2019-10-28 09:31:43 +01:00
Mark Paluch
b5bc4320aa DATAMONGO-2059 - Polishing.
Move query rewriting into CountQuery. Consider existing $and items during query rewrite.

Original pull request: #604.
2019-10-25 09:11:35 +02:00
Christoph Strobl
909c51d00a DATAMONGO-2059 - Replace usage of deprecated collection.count() with collection.countDocuments().
This commit switches from simple collection.count(), operating on potentially false collection statistic,  to countDocuments() using an aggregation for accurate results.
The transition required query modifications at some points because $match does not support $near and $nearSphere but require $geoWithin along with $center or $centerSphere which does not support $minDistance (see https://jira.mongodb.org/browse/SERVER-37043).
$geoWithin further more does not sort results by distance, but this fact can be ignored when just counting matches.

Examples:

{ location : { $near : [-73.99171, 40.738868], $maxDistance : 1.1 } }
{ location : { $geoWithin : { $center: [ [-73.99171, 40.738868], 1.1] } } }

{ location : { $near : [-73.99171, 40.738868], $minDistance : 0.1, $maxDistance : 1.1 } }
{$and :[ { $nor :[ { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 0.01] } } } ]}, { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 1.1] } } } ] }

Original pull request: #604.
2019-10-25 09:01:12 +02:00
Mark Paluch
4a04e82e86 DATAMONGO-2392 - Polishing.
Add author tags. Move integration tests to existing test class.
Apply more appropriate in existing tests assertions. Use diamond syntax.

Original pull request: #796.
2019-10-16 13:55:00 +02:00
Mark Paluch
1370653c93 DATAMONGO-2392 - Consistently use GridFS file Id instead of ObjectId.
We now consistently use GridFSFile.getId() to allow custom Id usage instead of enforcing the Id to be an ObjectId. Using the native Id allows interaction with files that use a custom Id type.

Original pull request: #796.
2019-10-16 13:54:57 +02:00
Nick Stolwijk
ebfcfb3834 DATAMONGO-2392 - Fix handling in ReactiveGridFsTemplate of GridFS files with custom id type.
Original pull request: #796.
2019-10-16 13:54:29 +02:00
Mark Paluch
77aafc597b DATAMONGO-2334 - After release cleanups. 2019-09-30 16:17:29 +02:00
Mark Paluch
a4503812bd DATAMONGO-2334 - Prepare next development iteration. 2019-09-30 16:17:28 +02:00
268 changed files with 6099 additions and 3123 deletions

38
.travis.yml Normal file
View File

@@ -0,0 +1,38 @@
language: java
jdk:
- oraclejdk8
before_install:
- mkdir -p downloads
- mkdir -p var/db var/log
- if [[ ! -d downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION} ]] ; then cd downloads && wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}.tgz && tar xzf mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}.tgz && cd ..; fi
- downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongod --version
- downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongod --dbpath var/db --replSet rs0 --fork --logpath var/log/mongod.log
- sleep 10
- |-
downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongo --eval "rs.initiate({_id: 'rs0', members:[{_id: 0, host: '127.0.0.1:27017'}]});"
sleep 15
env:
matrix:
- MONGO_VERSION=4.1.10
- MONGO_VERSION=4.0.4
- MONGO_VERSION=3.6.12
- MONGO_VERSION=3.4.20
global:
- PROFILE=ci
addons:
apt:
packages:
- oracle-java8-installer
sudo: false
cache:
directories:
- $HOME/.m2
- downloads
script: "mvn clean dependency:list test -P${PROFILE} -Dsort"

10
Jenkinsfile vendored
View File

@@ -3,7 +3,7 @@ pipeline {
triggers {
pollSCM 'H/10 * * * *'
upstream(upstreamProjects: "spring-data-commons/2.2.x", threshold: hudson.model.Result.SUCCESS)
upstream(upstreamProjects: "spring-data-commons/master", threshold: hudson.model.Result.SUCCESS)
}
options {
@@ -68,7 +68,7 @@ pipeline {
stage("test: baseline") {
when {
anyOf {
branch '2.2.x'
branch 'master'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -94,7 +94,7 @@ pipeline {
stage("Test other configurations") {
when {
anyOf {
branch '2.2.x'
branch 'master'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -143,7 +143,7 @@ pipeline {
stage('Release to artifactory') {
when {
anyOf {
branch '2.2.x'
branch 'master'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -175,7 +175,7 @@ pipeline {
stage('Publish documentation') {
when {
branch '2.2.x'
branch 'master'
}
agent {
docker {

14
pom.xml
View File

@@ -5,7 +5,7 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>3.0.0.M2</version>
<packaging>pom</packaging>
<name>Spring Data MongoDB</name>
@@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>2.3.0.M2</version>
</parent>
<modules>
@@ -26,9 +26,9 @@
<properties>
<project.type>multi</project.type>
<dist.id>spring-data-mongodb</dist.id>
<springdata.commons>2.2.8.RELEASE</springdata.commons>
<mongo>3.11.2</mongo>
<mongo.reactivestreams>1.12.0</mongo.reactivestreams>
<springdata.commons>2.3.0.M2</springdata.commons>
<mongo>3.12.0</mongo>
<mongo.reactivestreams>1.13.0</mongo.reactivestreams>
<jmh.version>1.19</jmh.version>
</properties>
@@ -134,8 +134,8 @@
<repositories>
<repository>
<id>spring-libs-release</id>
<url>https://repo.spring.io/libs-release</url>
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
</repository>
</repositories>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>3.0.0.M2</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>3.0.0.M2</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>3.0.0.M2</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -25,10 +25,8 @@ public class LazyLoadingException extends UncategorizedDataAccessException {
private static final long serialVersionUID = -7089224903873220037L;
/**
* Constructor for LazyLoadingException.
*
* @param msg the detail message.
* @param cause the exception thrown by underlying data access API.
* @param msg
* @param cause
*/
public LazyLoadingException(String msg, Throwable cause) {
super(msg, cause);

View File

@@ -37,7 +37,7 @@ public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvi
/**
* Creates a default {@link MongoDatabase} instance.
*
* @return never {@literal null}.
* @return
* @throws DataAccessException
*/
MongoDatabase getDb() throws DataAccessException;
@@ -46,7 +46,7 @@ public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvi
* Creates a {@link DB} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
* @throws DataAccessException
*/
MongoDatabase getDb(String dbName) throws DataAccessException;

View File

@@ -38,7 +38,7 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
/**
* Creates a default {@link MongoDatabase} instance.
*
* @return never {@literal null}.
* @return
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase() throws DataAccessException;
@@ -47,7 +47,7 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
* Creates a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase(String dbName) throws DataAccessException;

View File

@@ -42,21 +42,21 @@ public @interface EnableMongoAuditing {
/**
* Configures the {@link AuditorAware} bean to be used to lookup the current principal.
*
* @return empty {@link String} by default.
* @return
*/
String auditorAwareRef() default "";
/**
* Configures whether the creation and modification dates are set. Defaults to {@literal true}.
*
* @return {@literal true} by default.
* @return
*/
boolean setDates() default true;
/**
* Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
*
* @return {@literal true} by default.
* @return
*/
boolean modifyOnCreate() default true;
@@ -64,7 +64,7 @@ public @interface EnableMongoAuditing {
* Configures a {@link DateTimeProvider} bean name that allows customizing the {@link org.joda.time.DateTime} to be
* used for setting creation and modification dates.
*
* @return empty {@link String} by default.
* @return
*/
String dateTimeProviderRef() default "";
}

View File

@@ -89,7 +89,7 @@ public abstract class MongoConfigurationSupport {
/**
* Register custom {@link Converter}s in a {@link CustomConversions} object if required. These
* {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and
* {@link MongoMappingContext}. Returns an empty {@link MongoCustomConversions} instance by default.
* {@link #mongoMappingContext()}. Returns an empty {@link MongoCustomConversions} instance by default.
*
* @return must not be {@literal null}.
*/

View File

@@ -94,6 +94,7 @@ public interface BulkOperations {
* Add a list of updates to the bulk operation. For each update request, all matching documents are updated.
*
* @param updates Update operations to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations updateMulti(List<Pair<Query, Update>> updates);
@@ -104,6 +105,7 @@ public interface BulkOperations {
*
* @param query Update criteria.
* @param update Update operation to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations upsert(Query query, Update update);
@@ -113,6 +115,7 @@ public interface BulkOperations {
* else an insert.
*
* @param updates Updates/insert operations to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations upsert(List<Pair<Query, Update>> updates);

View File

@@ -29,7 +29,7 @@ import com.mongodb.client.MongoCollection;
* @author Grame Rocher
* @author Oliver Gierke
* @author John Brisbin
* @author Christoph Strobl
* @auhtor Christoph Strobl
* @since 1.0
*/
public interface CollectionCallback<T> {

View File

@@ -95,7 +95,7 @@ public class CollectionOptions {
/**
* Create new {@link CollectionOptions} with already given settings and capped set to {@literal true}. <br />
* <strong>NOTE</strong> Using capped collections requires defining {@link #size(long)}.
* <strong>NOTE</strong> Using capped collections requires defining {@link #size(int)}.
*
* @return new {@link CollectionOptions}.
* @since 2.0

View File

@@ -0,0 +1,227 @@
/*
* Copyright 2019-2020 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;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.springframework.data.geo.Point;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
* Value object representing a count query. Count queries using {@code $near} or {@code $nearSphere} require a rewrite
* to {@code $geoWithin}.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 3.0
*/
class CountQuery {
private Document source;
private CountQuery(Document source) {
this.source = source;
}
public static CountQuery of(Document source) {
return new CountQuery(source);
}
/**
* Returns the query {@link Document} that can be used with {@code countDocuments()}. Potentially rewrites the query
* to be usable with {@code countDocuments()}.
*
* @return the query {@link Document} that can be used with {@code countDocuments()}.
*/
public Document toQueryDocument() {
if (!requiresRewrite(source)) {
return source;
}
Document target = new Document();
for (Map.Entry<String, Object> entry : source.entrySet()) {
if (entry.getValue() instanceof Document && requiresRewrite(entry.getValue())) {
Document theValue = (Document) entry.getValue();
target.putAll(createGeoWithin(entry.getKey(), theValue, source.get("$and")));
continue;
}
if (entry.getValue() instanceof Collection && requiresRewrite(entry.getValue())) {
Collection<?> source = (Collection<?>) entry.getValue();
target.put(entry.getKey(), rewriteCollection(source));
continue;
}
if ("$and".equals(entry.getKey()) && target.containsKey("$and")) {
// Expect $and to be processed with Document and createGeoWithin.
continue;
}
target.put(entry.getKey(), entry.getValue());
}
return target;
}
/**
* @param valueToInspect
* @return {@code true} if the enclosing element needs to be rewritten.
*/
private boolean requiresRewrite(Object valueToInspect) {
if (valueToInspect instanceof Document) {
return requiresRewrite((Document) valueToInspect);
}
if (valueToInspect instanceof Collection) {
return requiresRewrite((Collection) valueToInspect);
}
return false;
}
private boolean requiresRewrite(Collection<?> collection) {
for (Object o : collection) {
if (o instanceof Document && requiresRewrite((Document) o)) {
return true;
}
}
return false;
}
private boolean requiresRewrite(Document document) {
if (containsNear(document)) {
return true;
}
for (Object entry : document.values()) {
if (requiresRewrite(entry)) {
return true;
}
}
return false;
}
private Collection<Object> rewriteCollection(Collection<?> source) {
Collection<Object> rewrittenCollection = new ArrayList<>(source.size());
for (Object item : source) {
if (item instanceof Document && requiresRewrite(item)) {
rewrittenCollection.add(CountQuery.of((Document) item).toQueryDocument());
} else {
rewrittenCollection.add(item);
}
}
return rewrittenCollection;
}
/**
* Rewrite the near query for field {@code key} to {@code $geoWithin}.
*
* @param key the queried field.
* @param source source {@link Document}.
* @param $and potentially existing {@code $and} condition.
* @return the rewritten query {@link Document}.
*/
private static Document createGeoWithin(String key, Document source, @Nullable Object $and) {
boolean spheric = source.containsKey("$nearSphere");
Object $near = spheric ? source.get("$nearSphere") : source.get("$near");
Number maxDistance = source.containsKey("$maxDistance") ? (Number) source.get("$maxDistance") : Double.MAX_VALUE;
List<Object> $centerMax = Arrays.asList(toCenterCoordinates($near), maxDistance);
Document $geoWithinMax = new Document("$geoWithin",
new Document(spheric ? "$centerSphere" : "$center", $centerMax));
if (!containsNearWithMinDistance(source)) {
return new Document(key, $geoWithinMax);
}
Number minDistance = (Number) source.get("$minDistance");
List<Object> $centerMin = Arrays.asList(toCenterCoordinates($near), minDistance);
Document $geoWithinMin = new Document("$geoWithin",
new Document(spheric ? "$centerSphere" : "$center", $centerMin));
List<Document> criteria = new ArrayList<>();
if ($and != null) {
if ($and instanceof Collection) {
criteria.addAll((Collection) $and);
} else {
throw new IllegalArgumentException(
"Cannot rewrite query as it contains an '$and' element that is not a Collection!: Offending element: "
+ $and);
}
}
criteria.add(new Document("$nor", Collections.singletonList(new Document(key, $geoWithinMin))));
criteria.add(new Document(key, $geoWithinMax));
return new Document("$and", criteria);
}
private static boolean containsNear(Document source) {
return source.containsKey("$near") || source.containsKey("$nearSphere");
}
private static boolean containsNearWithMinDistance(Document source) {
if (!containsNear(source)) {
return false;
}
return source.containsKey("$minDistance");
}
private static Object toCenterCoordinates(Object value) {
if (ObjectUtils.isArray(value)) {
return value;
}
if (value instanceof Point) {
return Arrays.asList(((Point) value).getX(), ((Point) value).getY());
}
if (value instanceof Document && ((Document) value).containsKey("x")) {
Document point = (Document) value;
return Arrays.asList(point.get("x"), point.get("y"));
}
return value;
}
}

View File

@@ -43,10 +43,9 @@ public interface CursorPreparer extends ReadPreferenceAware {
/**
* Prepare the given cursor (apply limits, skips and so on). Returns the prepared cursor.
*
* @param iterable must not be {@literal null}.
* @return never {@literal null}.
* @param cursor
*/
FindIterable<Document> prepare(FindIterable<Document> iterable);
FindIterable<Document> prepare(FindIterable<Document> cursor);
/**
* Apply query specific settings to {@link MongoCollection} and initate a find operation returning a
@@ -54,7 +53,7 @@ public interface CursorPreparer extends ReadPreferenceAware {
*
* @param collection must not be {@literal null}.
* @param find must not be {@literal null}.
* @return never {@literal null}.
* @return
* @throws IllegalArgumentException if one of the required arguments is {@literal null}.
* @since 2.2
*/

View File

@@ -23,7 +23,7 @@ import com.mongodb.MongoException;
/**
* An interface used by {@link MongoTemplate} for processing documents returned from a MongoDB query on a per-document
* basis. Implementations of this interface perform the actual work of prcoessing each document but don't need to worry
* about exception handling. {@link MongoException}s will be caught and translated by the calling MongoTemplate An
* about exception handling. {@MongoException}s will be caught and translated by the calling MongoTemplate An
* DocumentCallbackHandler is typically stateful: It keeps the result state within the object, to be available later for
* later inspection.
*

View File

@@ -66,7 +66,7 @@ class EntityOperations {
* Creates a new {@link Entity} for the given bean.
*
* @param entity must not be {@literal null}.
* @return new instance of {@link Entity}.
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> Entity<T> forEntity(T entity) {
@@ -89,7 +89,7 @@ class EntityOperations {
*
* @param entity must not be {@literal null}.
* @param conversionService must not be {@literal null}.
* @return new instance of {@link AdaptibleEntity}.
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> AdaptibleEntity<T> forEntity(T entity, ConversionService conversionService) {
@@ -108,10 +108,6 @@ class EntityOperations {
return AdaptibleMappedEntity.of(entity, context, conversionService);
}
/**
* @param entityClass should not be null.
* @return the {@link MongoPersistentEntity#getCollection() collection name}.
*/
public String determineCollectionName(@Nullable Class<?> entityClass) {
if (entityClass == null) {
@@ -142,7 +138,7 @@ class EntityOperations {
* {@code _id} if no identifier property can be found.
*
* @param type must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public String getIdPropertyName(Class<?> type) {

View File

@@ -88,10 +88,10 @@ public interface ExecutableAggregationOperation {
/**
* Apply pipeline operations as specified and stream all matching elements. <br />
* Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable}
* Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.Cursor}
*
* @return a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs
* to be closed. Never {@literal null}.
* @return a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.Cursor} that needs to be closed.
* Never {@literal null}.
*/
CloseableIterator<T> stream();
}

View File

@@ -117,8 +117,8 @@ public interface ExecutableFindOperation {
/**
* Stream all matching elements.
*
* @return a {@link Stream} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs to be
* closed. Never {@literal null}.
* @return a {@link Stream} that wraps the a Mongo DB {@link com.mongodb.Cursor} that needs to be closed. Never
* {@literal null}.
*/
Stream<T> stream();

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.mongodb.core;
import com.mongodb.ReadPreference;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@@ -25,7 +26,6 @@ import java.util.Optional;
import java.util.stream.Stream;
import org.bson.Document;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
@@ -37,7 +37,6 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import com.mongodb.ReadPreference;
import com.mongodb.client.FindIterable;
/**
@@ -258,9 +257,9 @@ class ExecutableFindOperationSupport implements ExecutableFindOperation {
* @see org.springframework.data.mongodb.core.CursorPreparer#prepare(com.mongodb.clientFindIterable)
*/
@Override
public FindIterable<Document> prepare(FindIterable<Document> iterable) {
public FindIterable<Document> prepare(FindIterable<Document> cursor) {
FindIterable<Document> target = delegate != null ? delegate.prepare(iterable) : iterable;
FindIterable<Document> target = delegate != null ? delegate.prepare(cursor) : cursor;
return limit.map(target::limit).orElse(target);
}

View File

@@ -17,8 +17,10 @@ package org.springframework.data.mongodb.core;
import java.util.Optional;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
import com.mongodb.client.result.UpdateResult;
@@ -151,13 +153,16 @@ public interface ExecutableUpdateOperation {
interface UpdateWithUpdate<T> {
/**
* Set the {@link Update} to be applied.
* Set the {@link UpdateDefinition} to be applied.
*
* @param update must not be {@literal null}.
* @return new instance of {@link TerminatingUpdate}.
* @throws IllegalArgumentException if update is {@literal null}.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
TerminatingUpdate<T> apply(Update update);
TerminatingUpdate<T> apply(UpdateDefinition update);
/**
* Specify {@code replacement} object.

View File

@@ -21,7 +21,7 @@ import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -67,7 +67,7 @@ class ExecutableUpdateOperationSupport implements ExecutableUpdateOperation {
@NonNull MongoTemplate template;
@NonNull Class domainType;
Query query;
@Nullable Update update;
@Nullable UpdateDefinition update;
@Nullable String collection;
@Nullable FindAndModifyOptions findAndModifyOptions;
@Nullable FindAndReplaceOptions findAndReplaceOptions;
@@ -76,10 +76,10 @@ class ExecutableUpdateOperationSupport implements ExecutableUpdateOperation {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ExecutableUpdateOperation.UpdateWithUpdate#apply(Update)
* @see org.springframework.data.mongodb.core.ExecutableUpdateOperation.UpdateWithUpdate#apply(org.springframework.data.mongodb.core.query.UpdateDefinition)
*/
@Override
public TerminatingUpdate<T> apply(Update update) {
public TerminatingUpdate<T> apply(UpdateDefinition update) {
Assert.notNull(update, "Update must not be null!");

View File

@@ -78,7 +78,7 @@ public class FindAndModifyOptions {
}
/**
* Create new {@link FindAndModifyOptions} based on option of given {@literal source}.
* Create new {@link FindAndModifyOptions} based on option of given {@litearl source}.
*
* @param source can be {@literal null}.
* @return new instance of {@link FindAndModifyOptions}.
@@ -117,8 +117,8 @@ public class FindAndModifyOptions {
/**
* Define the {@link Collation} specifying language-specific rules for string comparison.
*
* @param collation can be {@literal null}.
* @return this.
* @param collation
* @return
* @since 2.0
*/
public FindAndModifyOptions collation(@Nullable Collation collation) {
@@ -142,7 +142,7 @@ public class FindAndModifyOptions {
/**
* Get the {@link Collation} specifying language-specific rules for string comparison.
*
* @return never {@literal null}.
* @return
* @since 2.0
*/
public Optional<Collation> getCollation() {

View File

@@ -116,7 +116,7 @@ public class FindAndReplaceOptions {
/**
* Get the bit indicating to return the replacement document.
*
* @return {@literal true} if set.
* @return
*/
public boolean isReturnNew() {
return returnNew;
@@ -125,7 +125,7 @@ public class FindAndReplaceOptions {
/**
* Get the bit indicating if to create a new document if not exists.
*
* @return {@literal true} if set.
* @return
*/
public boolean isUpsert() {
return upsert;

View File

@@ -54,7 +54,7 @@ public interface FindPublisherPreparer extends ReadPreferenceAware {
*
* @param collection must not be {@literal null}.
* @param find must not be {@literal null}.
* @return never {@literal null}.
* @return
* @throws IllegalArgumentException if one of the required arguments is {@literal null}.
* @since 2.2
*/

View File

@@ -47,7 +47,7 @@ class GeoCommandStatistics {
* Creates a new {@link GeoCommandStatistics} from the given command result extracting the statistics.
*
* @param commandResult must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public static GeoCommandStatistics from(Document commandResult) {
@@ -61,7 +61,7 @@ class GeoCommandStatistics {
* Returns the average distance reported by the command result. Mitigating a removal of the field in case the command
* didn't return any result introduced in MongoDB 3.2 RC1.
*
* @return never {@literal null}, uses {@link Double#NaN} if {@literal avgDistance} does not exist.
* @return
* @see <a href="https://jira.mongodb.org/browse/SERVER-21024">MongoDB Jira SERVER-21024</a>
*/
public double getAverageDistance() {

View File

@@ -265,7 +265,7 @@ public abstract class MongoDbFactorySupport<C> implements MongoDbFactory {
factory.addAdvice(new SessionAwareMethodInterceptor<>(session, target, ClientSession.class, MongoDatabase.class,
this::proxyDatabase, MongoCollection.class, this::proxyCollection));
return targetType.cast(factory.getProxy(target.getClass().getClassLoader()));
return targetType.cast(factory.getProxy());
}
}

View File

@@ -27,6 +27,7 @@ import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
@@ -40,6 +41,7 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.util.CloseableIterator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -57,7 +59,7 @@ import com.mongodb.client.result.UpdateResult;
* Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. Not often used but
* a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be the target of a JDK
* proxy).
* <p />
* <p/>
* <strong>NOTE:</strong> Some operations cannot be executed within a MongoDB transaction. Please refer to the MongoDB
* specific documentation to learn more about <a href="https://docs.mongodb.com/manual/core/transactions/">Multi
* Document Transactions</a>.
@@ -78,7 +80,7 @@ public interface MongoOperations extends FluentMongoOperations {
* The collection name used for the specified class by this template.
*
* @param entityClass must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
String getCollectionName(Class<?> entityClass);
@@ -175,7 +177,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Obtain a {@link ClientSession session} bound instance of {@link SessionScoped} binding the {@link ClientSession}
* provided by the given {@link Supplier} to each and every command issued against MongoDB.
* <p />
* <p/>
* <strong>Note:</strong> It is up to the caller to manage the {@link ClientSession} lifecycle. Use the
* {@link SessionScoped#execute(SessionCallback, Consumer)} hook to potentially close the {@link ClientSession}.
*
@@ -211,7 +213,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Obtain a {@link ClientSession} bound instance of {@link MongoOperations}.
* <p />
* <p/>
* <strong>Note:</strong> It is up to the caller to manage the {@link ClientSession} lifecycle.
*
* @param session must not be {@literal null}.
@@ -360,7 +362,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Returns the {@link ScriptOperations} that can be performed on {@link com.mongodb.DB} level.
*
* @return never {@literal null}.
* @return
* @since 1.7
* @deprecated since 2.2. The {@code eval} command has been removed without replacement in MongoDB Server 4.2.0.
*/
@@ -883,12 +885,15 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @return the converted object that was updated before it was updated or {@literal null}, if not found.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
@Nullable
<T> T findAndModify(Query query, Update update, Class<T> entityClass);
<T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify <a/>
@@ -896,13 +901,16 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @param collectionName the collection to query. Must not be {@literal null}.
* @return the converted object that was updated before it was updated or {@literal null}, if not found.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
@Nullable
<T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName);
<T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify <a/>
@@ -911,15 +919,18 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification.
* @param update the {@link Update} to apply on matching documents.
* @param update the {@link UpdateDefinition} to apply on matching documents.
* @param options the {@link FindAndModifyOptions} holding additional information.
* @param entityClass the parametrized type.
* @return the converted object that was updated or {@literal null}, if not found. Depending on the value of
* {@link FindAndModifyOptions#isReturnNew()} this will either be the object as it was before the update or as
* it is after the update.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
@Nullable
<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass);
<T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify <a/>
@@ -928,16 +939,19 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param options the {@link FindAndModifyOptions} holding additional information. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @param collectionName the collection to query. Must not be {@literal null}.
* @return the converted object that was updated or {@literal null}, if not found. Depending on the value of
* {@link FindAndModifyOptions#isReturnNew()} this will either be the object as it was before the update or as
* it is after the update.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
@Nullable
<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
<T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass,
String collectionName);
/**
@@ -1286,99 +1300,112 @@ public interface MongoOperations extends FluentMongoOperations {
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, FindAndModifyOptions, Class, String)} instead.
* Use {@link #findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param entityClass class that determines the collection to use. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult upsert(Query query, Update update, Class<?> entityClass);
UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #upsert(Query, Update, Class, String)} to get full type specific support.
* <br />
* domain type information. Use {@link #upsert(Query, UpdateDefinition, Class, String)} to get full type specific
* support. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, FindAndModifyOptions, Class, String)} instead.
* Use {@link #findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult upsert(Query query, Update update, String collectionName);
UpdateResult upsert(Query query, UpdateDefinition update, String collectionName);
/**
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, FindAndModifyOptions, Class, String)} instead.
*
* combining the query document and the update document.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult upsert(Query query, Update update, Class<?> entityClass, String collectionName);
UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Updates the first object that is found in the collection of the entity class that matches the query document with
* the provided update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class)} instead.
* the provided update document.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class that determines the collection to use.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateFirst(Query query, Update update, Class<?> entityClass);
UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Updates the first object that is found in the specified collection that matches the query document criteria with
* the provided updated document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #updateFirst(Query, Update, Class, String)} to get full type specific support.
* domain type information. Use {@link #updateFirst(Query, UpdateDefinition, Class, String)} to get full type specific
* support.
* <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateFirst(Query query, Update update, String collectionName);
UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName);
/**
* Updates the first object that is found in the specified collection that matches the query document criteria with
* the provided updated document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateFirst(Query query, Update update, Class<?> entityClass, String collectionName);
UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Updates all objects that are found in the collection for the entity class that matches the query document criteria
@@ -1386,27 +1413,34 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateMulti(Query query, Update update, Class<?> entityClass);
UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Updates all objects that are found in the specified collection that matches the query document criteria with the
* provided updated document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #updateMulti(Query, Update, Class, String)} to get full type specific support.
* domain type information. Use {@link #updateMulti(Query, UpdateDefinition, Class, String)} to get full type specific
* support.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateMulti(Query query, Update update, String collectionName);
UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName);
/**
* Updates all objects that are found in the collection for the entity class that matches the query document criteria
@@ -1414,13 +1448,16 @@ public interface MongoOperations extends FluentMongoOperations {
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
UpdateResult updateMulti(Query query, Update update, Class<?> entityClass, String collectionName);
UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Remove the given object from the collection by {@literal id} and (if applicable) its
@@ -1520,7 +1557,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Returns the underlying {@link MongoConverter}.
*
* @return never {@literal null}.
* @return
*/
MongoConverter getConverter();
}

View File

@@ -35,6 +35,7 @@ import org.bson.codecs.Codec;
import org.bson.conversions.Bson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@@ -68,7 +69,9 @@ import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.aggregation.Fields;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
@@ -108,7 +111,6 @@ import org.springframework.data.mongodb.core.query.Meta;
import org.springframework.data.mongodb.core.query.Meta.CursorOption;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.core.validation.Validator;
@@ -435,7 +437,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@SuppressWarnings("ConstantConditions")
protected <T> CloseableIterator<T> doStream(Query query, final Class<?> entityType, String collectionName,
protected <T> CloseableIterator<T> doStream(Query query, Class<?> entityType, String collectionName,
Class<T> returnType) {
Assert.notNull(query, "Query must not be null!");
@@ -469,7 +471,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
*/
@Override
@SuppressWarnings("ConstantConditions")
public Document executeCommand(final String jsonCommand) {
public Document executeCommand(String jsonCommand) {
Assert.hasText(jsonCommand, "JsonCommand must not be null nor empty!");
@@ -482,7 +484,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
*/
@Override
@SuppressWarnings("ConstantConditions")
public Document executeCommand(final Document command) {
public Document executeCommand(Document command) {
Assert.notNull(command, "Command must not be null!");
@@ -653,7 +655,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#createCollection(java.lang.String)
*/
public MongoCollection<Document> createCollection(final String collectionName) {
public MongoCollection<Document> createCollection(String collectionName) {
Assert.notNull(collectionName, "CollectionName must not be null!");
@@ -664,8 +666,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#createCollection(java.lang.String, org.springframework.data.mongodb.core.CollectionOptions)
*/
public MongoCollection<Document> createCollection(final String collectionName,
final @Nullable CollectionOptions collectionOptions) {
public MongoCollection<Document> createCollection(String collectionName,
@Nullable CollectionOptions collectionOptions) {
Assert.notNull(collectionName, "CollectionName must not be null!");
return doCreateCollection(collectionName, convertToDocument(collectionOptions));
@@ -676,7 +678,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @see org.springframework.data.mongodb.core.MongoOperations#getCollection(java.lang.String)
*/
@SuppressWarnings("ConstantConditions")
public MongoCollection<Document> getCollection(final String collectionName) {
public MongoCollection<Document> getCollection(String collectionName) {
Assert.notNull(collectionName, "CollectionName must not be null!");
@@ -696,7 +698,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @see org.springframework.data.mongodb.core.ExecutableInsertOperation#getCollection(java.lang.String)
*/
@SuppressWarnings("ConstantConditions")
public boolean collectionExists(final String collectionName) {
public boolean collectionExists(String collectionName) {
Assert.notNull(collectionName, "CollectionName must not be null!");
@@ -727,15 +729,13 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Assert.notNull(collectionName, "CollectionName must not be null!");
execute(collectionName, new CollectionCallback<Void>() {
public Void doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
collection.drop();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Dropped collection [{}]",
collection.getNamespace() != null ? collection.getNamespace().getCollectionName() : collectionName);
}
return null;
execute(collectionName, (CollectionCallback<Void>) collection -> {
collection.drop();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Dropped collection [{}]",
collection.getNamespace() != null ? collection.getNamespace().getCollectionName() : collectionName);
}
return null;
});
}
@@ -1045,25 +1045,25 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
@Nullable
@Override
public <T> T findAndModify(Query query, Update update, Class<T> entityClass) {
public <T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass) {
return findAndModify(query, update, new FindAndModifyOptions(), entityClass, getCollectionName(entityClass));
}
@Nullable
@Override
public <T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName) {
public <T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName) {
return findAndModify(query, update, new FindAndModifyOptions(), entityClass, collectionName);
}
@Nullable
@Override
public <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass) {
public <T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass) {
return findAndModify(query, update, options, entityClass, getCollectionName(entityClass));
}
@Nullable
@Override
public <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
public <T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass,
String collectionName) {
Assert.notNull(query, "Query must not be null!");
@@ -1152,7 +1152,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@Override
public long count(final Query query, String collectionName) {
public long count(Query query, String collectionName) {
return count(query, null, collectionName);
}
@@ -1191,11 +1191,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
LOGGER.debug("Executing count: {} in collection: {}", serializeToJsonSafely(filter), collectionName);
}
if (MongoDatabaseUtils.isTransactionActive(getMongoDbFactory())) {
return execute(collectionName, collection -> collection.countDocuments(filter, options));
}
return execute(collectionName, collection -> collection.count(filter, options));
return execute(collectionName,
collection -> collection.countDocuments(CountQuery.of(filter).toQueryDocument(), options));
}
/*
@@ -1485,7 +1482,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@SuppressWarnings("ConstantConditions")
protected Object insertDocument(final String collectionName, final Document document, final Class<?> entityClass) {
protected Object insertDocument(String collectionName, Document document, Class<?> entityClass) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Inserting Document containing fields: {} in collection: {}", document.keySet(), collectionName);
@@ -1506,7 +1503,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
});
}
protected List<Object> insertDocumentList(final String collectionName, final List<Document> documents) {
protected List<Object> insertDocumentList(String collectionName, List<Document> documents) {
if (documents.isEmpty()) {
return Collections.emptyList();
@@ -1534,49 +1531,47 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
return MappedDocument.toIds(documents);
}
protected Object saveDocument(final String collectionName, final Document dbDoc, final Class<?> entityClass) {
protected Object saveDocument(String collectionName, Document dbDoc, Class<?> entityClass) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Saving Document containing fields: {}", dbDoc.keySet());
}
return execute(collectionName, new CollectionCallback<Object>() {
public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass,
dbDoc, null);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
return execute(collectionName, collection -> {
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass,
dbDoc, null);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MappedDocument mapped = MappedDocument.of(dbDoc);
MappedDocument mapped = MappedDocument.of(dbDoc);
if (!mapped.hasId()) {
if (writeConcernToUse == null) {
collection.insertOne(dbDoc);
} else {
collection.withWriteConcern(writeConcernToUse).insertOne(dbDoc);
}
} else if (writeConcernToUse == null) {
collection.replaceOne(mapped.getIdFilter(), dbDoc, new ReplaceOptions().upsert(true));
if (!mapped.hasId()) {
if (writeConcernToUse == null) {
collection.insertOne(dbDoc);
} else {
collection.withWriteConcern(writeConcernToUse).replaceOne(mapped.getIdFilter(), dbDoc,
new ReplaceOptions().upsert(true));
collection.withWriteConcern(writeConcernToUse).insertOne(dbDoc);
}
return mapped.getId();
} else if (writeConcernToUse == null) {
collection.replaceOne(mapped.getIdFilter(), dbDoc, new ReplaceOptions().upsert(true));
} else {
collection.withWriteConcern(writeConcernToUse).replaceOne(mapped.getIdFilter(), dbDoc,
new ReplaceOptions().upsert(true));
}
return mapped.getId();
});
}
@Override
public UpdateResult upsert(Query query, Update update, Class<?> entityClass) {
public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, true, false);
}
@Override
public UpdateResult upsert(Query query, Update update, String collectionName) {
public UpdateResult upsert(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, true, false);
}
@Override
public UpdateResult upsert(Query query, Update update, Class<?> entityClass, String collectionName) {
public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
Assert.notNull(entityClass, "EntityClass must not be null!");
@@ -1584,17 +1579,17 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@Override
public UpdateResult updateFirst(Query query, Update update, Class<?> entityClass) {
public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, false, false);
}
@Override
public UpdateResult updateFirst(final Query query, final Update update, final String collectionName) {
public UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, false, false);
}
@Override
public UpdateResult updateFirst(Query query, Update update, Class<?> entityClass, String collectionName) {
public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
Assert.notNull(entityClass, "EntityClass must not be null!");
@@ -1602,17 +1597,17 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@Override
public UpdateResult updateMulti(Query query, Update update, Class<?> entityClass) {
public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, false, true);
}
@Override
public UpdateResult updateMulti(final Query query, final Update update, String collectionName) {
public UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, false, true);
}
@Override
public UpdateResult updateMulti(final Query query, final Update update, Class<?> entityClass, String collectionName) {
public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
Assert.notNull(entityClass, "EntityClass must not be null!");
@@ -1620,8 +1615,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@SuppressWarnings("ConstantConditions")
protected UpdateResult doUpdate(final String collectionName, final Query query, final UpdateDefinition update,
@Nullable final Class<?> entityClass, final boolean upsert, final boolean multi) {
protected UpdateResult doUpdate(String collectionName, Query query, UpdateDefinition update,
@Nullable Class<?> entityClass, boolean upsert, boolean multi) {
Assert.notNull(collectionName, "CollectionName must not be null!");
Assert.notNull(query, "Query must not be null!");
@@ -1633,25 +1628,54 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
upsert ? "Upsert" : "UpdateFirst", serializeToJsonSafely(query.getSortObject()));
}
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
increaseVersionForUpdateIfNecessary(entity, update);
UpdateOptions opts = new UpdateOptions();
opts.upsert(upsert);
if (update.hasArrayFilters()) {
opts.arrayFilters(update.getArrayFilters().stream().map(ArrayFilter::asDocument).collect(Collectors.toList()));
}
Document queryObj = new Document();
if (query != null) {
queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
}
if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
queryObj.put("$isolated", 1);
}
if (update instanceof AggregationUpdate) {
AggregationOperationContext context = entityClass != null
? new RelaxedTypeBasedAggregationOperationContext(entityClass, mappingContext, queryMapper)
: Aggregation.DEFAULT_CONTEXT;
List<Document> pipeline = new AggregationUtil(queryMapper, mappingContext)
.createPipeline((AggregationUpdate) update, context);
return execute(collectionName, collection -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Calling update using query: {} and update: {} in collection: {}",
serializeToJsonSafely(queryObj), serializeToJsonSafely(pipeline), collectionName);
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName,
entityClass, update.getUpdateObject(), queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
return multi ? collection.updateMany(queryObj, pipeline, opts) : collection.updateOne(queryObj, pipeline, opts);
});
}
return execute(collectionName, collection -> {
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
increaseVersionForUpdateIfNecessary(entity, update);
UpdateOptions opts = new UpdateOptions();
opts.upsert(upsert);
if (update.hasArrayFilters()) {
opts.arrayFilters(update.getArrayFilters().stream().map(ArrayFilter::asDocument).collect(Collectors.toList()));
}
Document queryObj = new Document();
if (query != null) {
queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
}
operations.forType(entityClass) //
.getCollation(query) //
.map(Collation::toMongoCollation) //
@@ -1660,10 +1684,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Document updateObj = update instanceof MappedUpdate ? update.getUpdateObject()
: updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
queryObj.put("$isolated", 1);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj),
serializeToJsonSafely(updateObj), collectionName);
@@ -1683,11 +1703,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
return collection.replaceOne(queryObj, updateObj, replaceOptions);
} else {
if (multi) {
return collection.updateMany(queryObj, updateObj, opts);
} else {
return collection.updateOne(queryObj, updateObj, opts);
}
return multi ? collection.updateMany(queryObj, updateObj, opts)
: collection.updateOne(queryObj, updateObj, opts);
}
});
}
@@ -1740,14 +1757,14 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
@SuppressWarnings("ConstantConditions")
protected <T> DeleteResult doRemove(final String collectionName, final Query query,
@Nullable final Class<T> entityClass, boolean multi) {
protected <T> DeleteResult doRemove(String collectionName, Query query, @Nullable Class<T> entityClass,
boolean multi) {
Assert.notNull(query, "Query must not be null!");
Assert.hasText(collectionName, "Collection name must not be null or empty!");
final MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
final Document queryObject = queryMapper.getMappedObject(query.getQueryObject(), entity);
MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
Document queryObject = queryMapper.getMappedObject(query.getQueryObject(), entity);
return execute(collectionName, collection -> {
@@ -2145,7 +2162,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
protected <O> AggregationResults<O> doAggregate(Aggregation aggregation, String collectionName, Class<O> outputType,
AggregationOperationContext context) {
DocumentCallback<O> callback = new UnwrapAndReadDocumentCallback<>(mongoConverter, outputType, collectionName);
ReadDocumentCallback<O> callback = new ReadDocumentCallback<>(mongoConverter, outputType, collectionName);
AggregationOptions options = aggregation.getOptions();
AggregationUtil aggregationUtil = new AggregationUtil(queryMapper, mappingContext);
@@ -2190,6 +2207,10 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
options.getComment().ifPresent(aggregateIterable::comment);
if (options.hasExecutionTimeLimit()) {
aggregateIterable = aggregateIterable.maxTime(options.getMaxTime().toMillis(), TimeUnit.MILLISECONDS);
}
MongoIterable<O> iterable = aggregateIterable.map(val -> {
rawResult.add(val);
@@ -2651,7 +2672,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
@SuppressWarnings("ConstantConditions")
protected <T> T doFindAndModify(String collectionName, Document query, Document fields, Document sort,
Class<T> entityClass, Update update, @Nullable FindAndModifyOptions options) {
Class<T> entityClass, UpdateDefinition update, @Nullable FindAndModifyOptions options) {
EntityReader<? super T, Bson> readerToUse = this.mongoConverter;
@@ -2664,7 +2685,18 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
increaseVersionForUpdateIfNecessary(entity, update);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
Document mappedUpdate = updateMapper.getMappedObject(update.getUpdateObject(), entity);
Object mappedUpdate;
if (update instanceof AggregationUpdate) {
AggregationOperationContext context = entityClass != null
? new RelaxedTypeBasedAggregationOperationContext(entityClass, mappingContext, queryMapper)
: Aggregation.DEFAULT_CONTEXT;
mappedUpdate = new AggregationUtil(queryMapper, mappingContext).createPipeline((Aggregation) update, context);
} else {
mappedUpdate = updateMapper.getMappedObject(update.getUpdateObject(), entity);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
@@ -3038,11 +3070,11 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
private final Document query;
private final Document fields;
private final Document sort;
private final Document update;
private final Object update;
private final List<Document> arrayFilters;
private final FindAndModifyOptions options;
public FindAndModifyCallback(Document query, Document fields, Document sort, Document update,
public FindAndModifyCallback(Document query, Document fields, Document sort, Object update,
List<Document> arrayFilters, FindAndModifyOptions options) {
this.query = query;
this.fields = fields;
@@ -3070,7 +3102,13 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
opts.arrayFilters(arrayFilters);
}
return collection.findOneAndUpdate(query, update, opts);
if (update instanceof Document) {
return collection.findOneAndUpdate(query, (Document) update, opts);
} else if (update instanceof List) {
return collection.findOneAndUpdate(query, (List<Document>) update, opts);
}
throw new IllegalArgumentException(String.format("Using %s is not supported in findOneAndUpdate", update));
}
}
@@ -3155,13 +3193,12 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
@Nullable
public T doWith(@Nullable Document object) {
T source = null;
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, type, collectionName));
source = reader.read(type, object);
}
T source = reader.read(type, object);
if (null != source) {
maybeEmitEvent(new AfterConvertEvent<>(object, source, collectionName));
}
@@ -3201,7 +3238,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Class<?> typeToRead = targetType.isInterface() || targetType.isAssignableFrom(entityType) ? entityType
: targetType;
maybeEmitEvent(new AfterLoadEvent<>(object, targetType, collectionName));
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, targetType, collectionName));
}
Object source = reader.read(typeToRead, object);
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, source) : source;
@@ -3214,39 +3253,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
}
class UnwrapAndReadDocumentCallback<T> extends ReadDocumentCallback<T> {
public UnwrapAndReadDocumentCallback(EntityReader<? super T, Bson> reader, Class<T> type, String collectionName) {
super(reader, type, collectionName);
}
@Override
public T doWith(@Nullable Document object) {
if (object == null) {
return null;
}
Object idField = object.get(Fields.UNDERSCORE_ID);
if (!(idField instanceof Document)) {
return super.doWith(object);
}
Document toMap = new Document();
Document nested = (Document) idField;
toMap.putAll(nested);
for (String key : object.keySet()) {
if (!Fields.UNDERSCORE_ID.equals(key)) {
toMap.put(key, object.get(key));
}
}
return super.doWith(toMap);
}
}
class QueryCursorPreparer implements CursorPreparer {
private final Query query;
@@ -3262,9 +3268,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.CursorPreparer#prepare(com.mongodb.DBCursor)
*/
public FindIterable<Document> prepare(FindIterable<Document> iterable) {
public FindIterable<Document> prepare(FindIterable<Document> cursor) {
FindIterable<Document> cursorToUse = iterable;
FindIterable<Document> cursorToUse = cursor;
operations.forType(type).getCollation(query) //
.map(Collation::toMongoCollation) //
@@ -3522,19 +3528,5 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
// native MongoDB objects that offer methods with ClientSession must not be proxied.
return delegate.getDb();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoTemplate#doCount(java.lang.String, org.bson.Document, com.mongodb.client.model.CountOptions)
*/
@Override
protected long doCount(String collectionName, Document filter, CountOptions options) {
if (!session.hasActiveTransaction()) {
return super.doCount(collectionName, filter, options);
}
return execute(collectionName, collection -> collection.countDocuments(filter, options));
}
}
}

View File

@@ -29,6 +29,7 @@ import org.springframework.data.geo.GeoResult;
import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
@@ -39,6 +40,7 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
import org.springframework.transaction.reactive.TransactionalOperator;
import org.springframework.util.Assert;
@@ -678,11 +680,14 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @return the converted object that was updated before it was updated.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
<T> Mono<T> findAndModify(Query query, Update update, Class<T> entityClass);
<T> Mono<T> findAndModify(Query query, UpdateDefinition update, Class<T> entityClass);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify<a/>
@@ -690,12 +695,15 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @param collectionName the collection to query. Must not be {@literal null}.
* @return the converted object that was updated before it was updated.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
<T> Mono<T> findAndModify(Query query, Update update, Class<T> entityClass, String collectionName);
<T> Mono<T> findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify<a/>
@@ -704,13 +712,16 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification.
* @param update the {@link Update} to apply on matching documents.
* @param update the {@link UpdateDefinition} to apply on matching documents.
* @param options the {@link FindAndModifyOptions} holding additional information.
* @param entityClass the parametrized type.
* @return the converted object that was updated. Depending on the value of {@link FindAndModifyOptions#isReturnNew()}
* this will either be the object as it was before the update or as it is after the update.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
<T> Mono<T> findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass);
<T> Mono<T> findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass);
/**
* Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify<a/>
@@ -719,14 +730,17 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
* fields specification. Must not be {@literal null}.
* @param update the {@link Update} to apply on matching documents. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
* @param options the {@link FindAndModifyOptions} holding additional information. Must not be {@literal null}.
* @param entityClass the parametrized type. Must not be {@literal null}.
* @param collectionName the collection to query. Must not be {@literal null}.
* @return the converted object that was updated. Depending on the value of {@link FindAndModifyOptions#isReturnNew()}
* this will either be the object as it was before the update or as it is after the update.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
<T> Mono<T> findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
<T> Mono<T> findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass,
String collectionName);
/**
@@ -1149,99 +1163,111 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class)} instead.
* Use {@link #findAndModify(Query, UpdateDefinition, Class)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param entityClass class that determines the collection to use. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> upsert(Query query, Update update, Class<?> entityClass);
Mono<UpdateResult> upsert(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #upsert(Query, Update, Class, String)} to get full type specific support.
* <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class, String)} instead.
* domain type information. Use {@link #upsert(Query, UpdateDefinition, Class, String)} to get full type specific
* support.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> upsert(Query query, Update update, String collectionName);
Mono<UpdateResult> upsert(Query query, UpdateDefinition update, String collectionName);
/**
* Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
* combining the query document and the update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class, String)} instead.
* combining the query document and the update document.
*
* @param query the query document that specifies the criteria used to select a record to be upserted. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing
* object. Must not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing object. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> upsert(Query query, Update update, Class<?> entityClass, String collectionName);
Mono<UpdateResult> upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Updates the first object that is found in the collection of the entity class that matches the query document with
* the provided update document. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class)} instead.
* Use {@link #findAndModify(Query, UpdateDefinition, Class)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class that determines the collection to use.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateFirst(Query query, Update update, Class<?> entityClass);
Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Updates the first object that is found in the specified collection that matches the query document criteria with
* the provided updated document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #updateFirst(Query, Update, Class, String)} to get full type specific support.
* <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, UpdateDefinition, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
*/
Mono<UpdateResult> updateFirst(Query query, Update update, String collectionName);
/**
* Updates the first object that is found in the specified collection that matches the query document criteria with
* the provided updated document. <br />
* domain type information. Use {@link #updateFirst(Query, UpdateDefinition, Class, String)} to get full type specific
* support. <br />
* <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
* Use {@link #findAndModify(Query, Update, Class, String)} instead.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, String collectionName);
/**
* Updates the first object that is found in the specified collection that matches the query document criteria with
* the provided updated document. <br />
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateFirst(Query query, Update update, Class<?> entityClass, String collectionName);
Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Updates all objects that are found in the collection for the entity class that matches the query document criteria
@@ -1249,27 +1275,34 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateMulti(Query query, Update update, Class<?> entityClass);
Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, Class<?> entityClass);
/**
* Updates all objects that are found in the specified collection that matches the query document criteria with the
* provided updated document. <br />
* <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
* domain type information. Use {@link #updateMulti(Query, Update, Class, String)} to get full type specific support.
* domain type information. Use {@link #updateMulti(Query, UpdateDefinition, Class, String)} to get full type specific
* support.
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateMulti(Query query, Update update, String collectionName);
Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, String collectionName);
/**
* Updates all objects that are found in the collection for the entity class that matches the query document criteria
@@ -1277,13 +1310,16 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*
* @param query the query document that specifies the criteria used to select a record to be updated. Must not be
* {@literal null}.
* @param update the update document that contains the updated object or $ operators to manipulate the existing. Must
* not be {@literal null}.
* @param update the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
* the existing. Must not be {@literal null}.
* @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
* @param collectionName name of the collection to update the object in. Must not be {@literal null}.
* @return the {@link UpdateResult} which lets you access the results of the previous write.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
Mono<UpdateResult> updateMulti(Query query, Update update, Class<?> entityClass, String collectionName);
Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);
/**
* Remove the given object from the collection by id.
@@ -1535,7 +1571,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
/**
* Returns the underlying {@link MongoConverter}.
*
* @return never {@literal null}.
* @return
*/
MongoConverter getConverter();
@@ -1543,7 +1579,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* The collection name used for the specified class by this template.
*
* @param entityClass must not be {@literal null}.
* @return never {@literal null}.
* @return
* @since 2.1
*/
String getCollectionName(Class<?> entityClass);

View File

@@ -40,7 +40,6 @@ import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@@ -70,7 +69,9 @@ import org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
@@ -106,7 +107,6 @@ import org.springframework.data.mongodb.core.query.Meta;
import org.springframework.data.mongodb.core.query.Meta.CursorOption;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.core.validation.Validator;
@@ -123,6 +123,9 @@ import org.springframework.util.StringUtils;
import com.mongodb.ClientSessionOptions;
import com.mongodb.CursorType;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
@@ -320,7 +323,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/**
* Configures the {@link WriteConcern} to be used with the template. If none is configured the {@link WriteConcern}
* configured on the {@link MongoDbFactory} will apply.
* configured on the {@link MongoDbFactory} will apply. If you configured a {@link Mongo} instance no
* {@link WriteConcern} will be used.
*
* @param writeConcern can be {@literal null}.
*/
@@ -1070,6 +1074,10 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
.map(Collation::toMongoCollation) //
.ifPresent(cursor::collation);
if (options.hasExecutionTimeLimit()) {
cursor = cursor.maxTime(options.getMaxTime().toMillis(), TimeUnit.MILLISECONDS);
}
return Flux.from(cursor).map(readCallback::doWith);
}
@@ -1118,36 +1126,38 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class)
*/
public <T> Mono<T> findAndModify(Query query, Update update, Class<T> entityClass) {
public <T> Mono<T> findAndModify(Query query, UpdateDefinition update, Class<T> entityClass) {
return findAndModify(query, update, new FindAndModifyOptions(), entityClass, getCollectionName(entityClass));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class, java.lang.String)
*/
public <T> Mono<T> findAndModify(Query query, Update update, Class<T> entityClass, String collectionName) {
public <T> Mono<T> findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName) {
return findAndModify(query, update, new FindAndModifyOptions(), entityClass, collectionName);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, org.springframework.data.mongodb.core.FindAndModifyOptions, java.lang.Class)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, org.springframework.data.mongodb.core.FindAndModifyOptions, java.lang.Class)
*/
public <T> Mono<T> findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass) {
public <T> Mono<T> findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options,
Class<T> entityClass) {
return findAndModify(query, update, options, entityClass, getCollectionName(entityClass));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, org.springframework.data.mongodb.core.FindAndModifyOptions, java.lang.Class, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndModify(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, org.springframework.data.mongodb.core.FindAndModifyOptions, java.lang.Class, java.lang.String)
*/
public <T> Mono<T> findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
String collectionName) {
public <T> Mono<T> findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options,
Class<T> entityClass, String collectionName) {
Assert.notNull(options, "Options must not be null! ");
Assert.notNull(entityClass, "Entity class must not be null!");
FindAndModifyOptions optionsToUse = FindAndModifyOptions.of(options);
@@ -1158,7 +1168,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
if (!optionsToUse.getCollation().isPresent()) {
operations.forType(entityClass).getCollation(query).ifPresent(optionsToUse::collation);
;
}
return doFindAndModify(collectionName, query.getQueryObject(), query.getFieldsObject(),
@@ -1297,9 +1306,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
*/
protected Mono<Long> doCount(String collectionName, Document filter, CountOptions options) {
return ReactiveMongoDatabaseUtils.isTransactionActive(mongoDatabaseFactory) //
.flatMap(txActive -> createMono(collectionName,
collection -> txActive ? collection.countDocuments(filter, options) : collection.count(filter, options)));
return createMono(collectionName,
collection -> collection.countDocuments(CountQuery.of(filter).toQueryDocument(), options));
}
/*
@@ -1681,73 +1689,75 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class)
*/
public Mono<UpdateResult> upsert(Query query, Update update, Class<?> entityClass) {
public Mono<UpdateResult> upsert(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, true, false);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.String)
*/
public Mono<UpdateResult> upsert(Query query, Update update, String collectionName) {
public Mono<UpdateResult> upsert(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, true, false);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class, java.lang.String)
*/
public Mono<UpdateResult> upsert(Query query, Update update, Class<?> entityClass, String collectionName) {
public Mono<UpdateResult> upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
return doUpdate(collectionName, query, update, entityClass, true, false);
}
/*
* (non-Javadoc))
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class)
*/
public Mono<UpdateResult> updateFirst(Query query, Update update, Class<?> entityClass) {
public Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, false, false);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.String)
*/
public Mono<UpdateResult> updateFirst(Query query, Update update, String collectionName) {
public Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, false, false);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateFirst(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class, java.lang.String)
*/
public Mono<UpdateResult> updateFirst(Query query, Update update, Class<?> entityClass, String collectionName) {
public Mono<UpdateResult> updateFirst(Query query, UpdateDefinition update, Class<?> entityClass,
String collectionName) {
return doUpdate(collectionName, query, update, entityClass, false, false);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class)
*/
public Mono<UpdateResult> updateMulti(Query query, Update update, Class<?> entityClass) {
public Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, Class<?> entityClass) {
return doUpdate(getCollectionName(entityClass), query, update, entityClass, false, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.String)
*/
public Mono<UpdateResult> updateMulti(Query query, Update update, String collectionName) {
public Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, String collectionName) {
return doUpdate(collectionName, query, update, null, false, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update, java.lang.Class, java.lang.String)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.UpdateDefinition, java.lang.Class, java.lang.String)
*/
public Mono<UpdateResult> updateMulti(Query query, Update update, Class<?> entityClass, String collectionName) {
public Mono<UpdateResult> updateMulti(Query query, UpdateDefinition update, Class<?> entityClass,
String collectionName) {
return doUpdate(collectionName, query, update, entityClass, false, true);
}
@@ -1761,56 +1771,87 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
}
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
increaseVersionForUpdateIfNecessary(entity, update);
Flux<UpdateResult> result = execute(collectionName, collection -> {
Document queryObj = queryMapper.getMappedObject(query.getQueryObject(), entity);
increaseVersionForUpdateIfNecessary(entity, update);
UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
operations.forType(entityClass).getCollation(query) //
.map(Collation::toMongoCollation) //
.ifPresent(updateOptions::collation);
Document queryObj = queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document()
: updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (update.hasArrayFilters()) {
updateOptions.arrayFilters(update.getArrayFilters().stream().map(ArrayFilter::asDocument)
.map(it -> queryMapper.getMappedObject(it, entity)).collect(Collectors.toList()));
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s",
serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
}
if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
queryObj.put("$isolated", 1);
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass,
updateObj, queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
Flux<UpdateResult> result;
UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
operations.forType(entityClass).getCollation(query) //
.map(Collation::toMongoCollation) //
.ifPresent(updateOptions::collation);
if (update instanceof AggregationUpdate) {
if (update.hasArrayFilters()) {
updateOptions.arrayFilters(update.getArrayFilters().stream().map(ArrayFilter::asDocument)
.map(it -> queryMapper.getMappedObject(it, entity)).collect(Collectors.toList()));
}
AggregationOperationContext context = entityClass != null
? new RelaxedTypeBasedAggregationOperationContext(entityClass, mappingContext, queryMapper)
: Aggregation.DEFAULT_CONTEXT;
if (!UpdateMapper.isUpdateObject(updateObj)) {
List<Document> pipeline = new AggregationUtil(queryMapper, mappingContext)
.createPipeline((AggregationUpdate) update, context);
ReplaceOptions replaceOptions = new ReplaceOptions();
replaceOptions.upsert(updateOptions.isUpsert());
replaceOptions.collation(updateOptions.getCollation());
result = execute(collectionName, collection -> {
return collectionToUse.replaceOne(queryObj, updateObj, replaceOptions);
}
if (multi) {
return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
}
return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
}).doOnNext(updateResult -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s",
serializeToJsonSafely(queryObj), serializeToJsonSafely(pipeline), collectionName));
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName,
entityClass, update.getUpdateObject(), queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
return multi ? collection.updateMany(queryObj, pipeline, updateOptions)
: collection.updateOne(queryObj, pipeline, updateOptions);
});
} else {
result = execute(collectionName, collection -> {
Document updateObj = updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s",
serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName,
entityClass, updateObj, queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
if (!UpdateMapper.isUpdateObject(updateObj)) {
ReplaceOptions replaceOptions = new ReplaceOptions();
replaceOptions.upsert(updateOptions.isUpsert());
replaceOptions.collation(updateOptions.getCollation());
return collectionToUse.replaceOne(queryObj, updateObj, replaceOptions);
}
return multi ? collectionToUse.updateMany(queryObj, updateObj, updateOptions)
: collectionToUse.updateOne(queryObj, updateObj, updateOptions);
});
}
result = result.doOnNext(updateResult -> {
if (entity != null && entity.hasVersionProperty() && !multi) {
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
Document queryObj = query == null ? new Document()
: queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document()
: updateMapper.getMappedObject(update.getUpdateObject(), entity);
Document updateObj = updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (containsVersionProperty(queryObj, entity))
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
+ updateObj.toString() + " to collection " + collectionName);
@@ -2044,8 +2085,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
if (query == null) {
// TODO: clean up
LOGGER.debug(String.format("find for class: %s in collection: %s", entityClass, collectionName));
LOGGER.debug(String.format("Tail for class: %s in collection: %s", entityClass, collectionName));
return executeFindMultiInternal(
collection -> new FindCallback(null).doInCollection(collection).cursorType(CursorType.TailableAwait),
@@ -2397,8 +2437,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* @param query the query document that specifies the criteria used to find a record.
* @param fields the document that specifies the fields to be returned.
* @param entityClass the parameterized type of the returned list.
* @param preparer allows for customization of the {@link com.mongodb.client.FindIterable} used when iterating over
* the result set, (apply limits, skips and so on).
* @param preparer allows for customization of the {@link DBCursor} used when iterating over the result set, (apply
* limits, skips and so on).
* @return the {@link List} of converted objects.
*/
protected <T> Flux<T> doFind(String collectionName, Document query, Document fields, Class<T> entityClass,
@@ -2536,16 +2576,25 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
}
protected <T> Mono<T> doFindAndModify(String collectionName, Document query, Document fields, Document sort,
Class<T> entityClass, Update update, FindAndModifyOptions options) {
Class<T> entityClass, UpdateDefinition update, FindAndModifyOptions options) {
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
increaseVersionForUpdateIfNecessary(entity, update);
return Mono.defer(() -> {
increaseVersionForUpdateIfNecessary(entity, update);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
Document mappedUpdate = updateMapper.getMappedObject(update.getUpdateObject(), entity);
Object mappedUpdate;
if (update instanceof AggregationUpdate) {
AggregationOperationContext context = new RelaxedTypeBasedAggregationOperationContext(entityClass,
mappingContext, queryMapper);
mappedUpdate = new AggregationUtil(queryMapper, mappingContext).createPipeline((Aggregation) update, context);
} else {
mappedUpdate = updateMapper.getMappedObject(update.getUpdateObject(), entity);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
@@ -2809,7 +2858,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/**
* Simple {@link ReactiveCollectionCallback} that takes a query {@link Document} plus an optional fields specification
* {@link Document} and executes that against the {@link MongoCollection}.
* {@link Document} and executes that against the {@link DBCollection}.
*
* @author Oliver Gierke
* @author Thomas Risberg
@@ -2922,7 +2971,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
private final Document query;
private final Document fields;
private final Document sort;
private final Document update;
private final Object update;
private final List<Document> arrayFilters;
private final FindAndModifyOptions options;
@@ -2941,7 +2990,14 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
FindOneAndUpdateOptions findOneAndUpdateOptions = convertToFindOneAndUpdateOptions(options, fields, sort,
arrayFilters);
return collection.findOneAndUpdate(query, update, findOneAndUpdateOptions);
if (update instanceof Document) {
return collection.findOneAndUpdate(query, (Document) update, findOneAndUpdateOptions);
} else if (update instanceof List) {
return collection.findOneAndUpdate(query, (List<Document>) update, findOneAndUpdateOptions);
}
return Flux
.error(new IllegalArgumentException(String.format("Using %s is not supported in findOneAndUpdate", update)));
}
private static FindOneAndUpdateOptions convertToFindOneAndUpdateOptions(FindAndModifyOptions options,
@@ -3320,20 +3376,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
// native MongoDB objects that offer methods with ClientSession must not be proxied.
return delegate.getMongoDatabase();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoTemplate#count(java.lang.String, org.bson.Document, com.mongodb.client.model.CountOptions)
*/
@Override
public Mono<Long> doCount(String collectionName, Document filter, CountOptions options) {
if (!session.hasActiveTransaction()) {
return super.doCount(collectionName, filter, options);
}
return createMono(collectionName, collection -> collection.countDocuments(filter, options));
}
}
@RequiredArgsConstructor

View File

@@ -15,6 +15,8 @@
*/
package org.springframework.data.mongodb.core;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import reactor.core.publisher.Mono;
import org.springframework.data.mongodb.core.query.Query;
@@ -118,13 +120,16 @@ public interface ReactiveUpdateOperation {
interface UpdateWithUpdate<T> {
/**
* Set the {@link org.springframework.data.mongodb.core.query.Update} to be applied.
* Set the {@link UpdateDefinition} to be applied.
*
* @param update must not be {@literal null}.
* @return new instance of {@link TerminatingUpdate}. Never {@literal null}.
* @throws IllegalArgumentException if update is {@literal null}.
* @since 3.0
* @see Update
* @see AggregationUpdate
*/
TerminatingUpdate<T> apply(org.springframework.data.mongodb.core.query.Update update);
TerminatingUpdate<T> apply(UpdateDefinition update);
/**
* Specify {@code replacement} object.

View File

@@ -63,7 +63,7 @@ class ReactiveUpdateOperationSupport implements ReactiveUpdateOperation {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<?> domainType;
Query query;
org.springframework.data.mongodb.core.query.Update update;
org.springframework.data.mongodb.core.query.UpdateDefinition update;
@Nullable String collection;
@Nullable FindAndModifyOptions findAndModifyOptions;
@Nullable FindAndReplaceOptions findAndReplaceOptions;
@@ -72,10 +72,10 @@ class ReactiveUpdateOperationSupport implements ReactiveUpdateOperation {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveUpdateOperation.UpdateWithUpdate#apply(org.springframework.data.mongodb.core.query.Update)
* @see org.springframework.data.mongodb.core.ReactiveUpdateOperation.UpdateWithUpdate#apply(org.springframework.data.mongodb.core.query.UpdateDefinition)
*/
@Override
public TerminatingUpdate<T> apply(org.springframework.data.mongodb.core.query.Update update) {
public TerminatingUpdate<T> apply(org.springframework.data.mongodb.core.query.UpdateDefinition update) {
Assert.notNull(update, "Update must not be null!");

View File

@@ -242,7 +242,7 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
factory.addAdvice(new SessionAwareMethodInterceptor<>(session, target, ClientSession.class, MongoDatabase.class,
this::proxyDatabase, MongoCollection.class, this::proxyCollection));
return targetType.cast(factory.getProxy(target.getClass().getClassLoader()));
return targetType.cast(factory.getProxy());
}
}
}

View File

@@ -16,8 +16,8 @@
package org.springframework.data.mongodb.core;
/**
* Enum to represent how strict the check of {@link com.mongodb.WriteConcernResult} shall be. It can either be skipped
* entirely (use {@link #NONE}) or cause an exception to be thrown {@link #EXCEPTION}.
* Enum to represent how strict the check of {@link com.mongodb.WriteResult} shall be. It can either be skipped entirely
* (use {@link #NONE}) or cause an exception to be thrown {@link #EXCEPTION}.
*
* @author Thomas Risberg
* @author Oliver Gierke

View File

@@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core.aggregation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
@@ -101,14 +100,14 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
return value;
}
protected List<Object> append(Object value, Expand expandList) {
protected List<Object> append(Object value) {
if (this.value instanceof List) {
List<Object> clone = new ArrayList<Object>((List) this.value);
if (value instanceof Collection && Expand.EXPAND_VALUES.equals(expandList)) {
clone.addAll((Collection<?>) value);
if (value instanceof List) {
clone.addAll((List) value);
} else {
clone.add(value);
}
@@ -118,17 +117,6 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
return Arrays.asList(this.value, value);
}
/**
* Expand a nested list of values to single entries or keep the list.
*/
protected enum Expand {
EXPAND_VALUES, KEEP_SOURCE
}
protected List<Object> append(Object value) {
return append(value, Expand.EXPAND_VALUES);
}
@SuppressWarnings("unchecked")
protected java.util.Map<String, Object> append(String key, Object value) {

View File

@@ -34,7 +34,7 @@ public class AccumulatorOperators {
* Take the numeric value referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link AccumulatorOperatorFactory}.
* @return
*/
public static AccumulatorOperatorFactory valueOf(String fieldReference) {
return new AccumulatorOperatorFactory(fieldReference);
@@ -44,7 +44,7 @@ public class AccumulatorOperators {
* Take the numeric value referenced resulting from given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link AccumulatorOperatorFactory}.
* @return
*/
public static AccumulatorOperatorFactory valueOf(AggregationExpression expression) {
return new AccumulatorOperatorFactory(expression);
@@ -86,7 +86,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and calculates and
* returns the sum.
*
* @return new instance of {@link Sum}.
* @return
*/
public Sum sum() {
return usesFieldRef() ? Sum.sumOf(fieldReference) : Sum.sumOf(expression);
@@ -96,7 +96,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and returns the
* average value.
*
* @return new instance of {@link Avg}.
* @return
*/
public Avg avg() {
return usesFieldRef() ? Avg.avgOf(fieldReference) : Avg.avgOf(expression);
@@ -106,7 +106,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and returns the
* maximum value.
*
* @return new instance of {@link Max}.
* @return
*/
public Max max() {
return usesFieldRef() ? Max.maxOf(fieldReference) : Max.maxOf(expression);
@@ -116,7 +116,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and returns the
* minimum value.
*
* @return new instance of {@link Min}.
* @return
*/
public Min min() {
return usesFieldRef() ? Min.minOf(fieldReference) : Min.minOf(expression);
@@ -126,7 +126,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and calculates the
* population standard deviation of the input values.
*
* @return new instance of {@link StdDevPop}.
* @return
*/
public StdDevPop stdDevPop() {
return usesFieldRef() ? StdDevPop.stdDevPopOf(fieldReference) : StdDevPop.stdDevPopOf(expression);
@@ -136,7 +136,7 @@ public class AccumulatorOperators {
* Creates new {@link AggregationExpression} that takes the associated numeric value expression and calculates the
* sample standard deviation of the input values.
*
* @return new instance of {@link StdDevSamp}.
* @return
*/
public StdDevSamp stdDevSamp() {
return usesFieldRef() ? StdDevSamp.stdDevSampOf(fieldReference) : StdDevSamp.stdDevSampOf(expression);
@@ -167,7 +167,7 @@ public class AccumulatorOperators {
* Creates new {@link Sum}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Sum}.
* @return
*/
public static Sum sumOf(String fieldReference) {
@@ -179,7 +179,7 @@ public class AccumulatorOperators {
* Creates new {@link Sum}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Sum}.
* @return
*/
public static Sum sumOf(AggregationExpression expression) {
@@ -192,7 +192,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Sum}.
* @return
*/
public Sum and(String fieldReference) {
@@ -205,7 +205,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Sum}.
* @return
*/
public Sum and(AggregationExpression expression) {
@@ -264,7 +264,7 @@ public class AccumulatorOperators {
* Creates new {@link Avg}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Avg}.
* @return
*/
public static Avg avgOf(String fieldReference) {
@@ -276,7 +276,7 @@ public class AccumulatorOperators {
* Creates new {@link Avg}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Avg}.
* @return
*/
public static Avg avgOf(AggregationExpression expression) {
@@ -289,7 +289,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Avg}.
* @return
*/
public Avg and(String fieldReference) {
@@ -302,7 +302,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Avg}.
* @return
*/
public Avg and(AggregationExpression expression) {
@@ -347,7 +347,7 @@ public class AccumulatorOperators {
* Creates new {@link Max}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Max}.
* @return
*/
public static Max maxOf(String fieldReference) {
@@ -359,7 +359,7 @@ public class AccumulatorOperators {
* Creates new {@link Max}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Max}.
* @return
*/
public static Max maxOf(AggregationExpression expression) {
@@ -372,7 +372,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Max}.
* @return
*/
public Max and(String fieldReference) {
@@ -385,7 +385,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Max}.
* @return
*/
public Max and(AggregationExpression expression) {
@@ -430,7 +430,7 @@ public class AccumulatorOperators {
* Creates new {@link Min}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Min}.
* @return
*/
public static Min minOf(String fieldReference) {
@@ -442,7 +442,7 @@ public class AccumulatorOperators {
* Creates new {@link Min}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Min}.
* @return
*/
public static Min minOf(AggregationExpression expression) {
@@ -455,7 +455,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Min}.
* @return
*/
public Min and(String fieldReference) {
@@ -468,7 +468,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Min}.
* @return
*/
public Min and(AggregationExpression expression) {
@@ -513,7 +513,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevPop}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StdDevPop}.
* @return
*/
public static StdDevPop stdDevPopOf(String fieldReference) {
@@ -525,7 +525,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevPop} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StdDevPop}.
* @return
*/
public static StdDevPop stdDevPopOf(AggregationExpression expression) {
@@ -538,7 +538,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StdDevPop}.
* @return
*/
public StdDevPop and(String fieldReference) {
@@ -551,7 +551,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StdDevPop}.
* @return
*/
public StdDevPop and(AggregationExpression expression) {
@@ -596,7 +596,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevSamp}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StdDevSamp}.
* @return
*/
public static StdDevSamp stdDevSampOf(String fieldReference) {
@@ -608,7 +608,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevSamp}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StdDevSamp}.
* @return
*/
public static StdDevSamp stdDevSampOf(AggregationExpression expression) {
@@ -621,7 +621,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StdDevSamp}.
* @return
*/
public StdDevSamp and(String fieldReference) {
@@ -634,7 +634,7 @@ public class AccumulatorOperators {
* <strong>NOTE:</strong> Only possible in {@code $project} stage.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StdDevSamp}.
* @return
*/
public StdDevSamp and(AggregationExpression expression) {

View File

@@ -115,12 +115,23 @@ public class Aggregation {
return new Aggregation(operations);
}
/**
* Creates a new {@link AggregationUpdate} from the given {@link AggregationOperation}s.
*
* @param operations can be {@literal empty} but must not be {@literal null}.
* @return new instance of {@link AggregationUpdate}.
* @since 3.0
*/
public static AggregationUpdate newUpdate(AggregationOperation... operations) {
return AggregationUpdate.from(Arrays.asList(operations));
}
/**
* Returns a copy of this {@link Aggregation} with the given {@link AggregationOptions} set. Note that options are
* supported in MongoDB version 2.6+.
*
* @param options must not be {@literal null}.
* @return new instance of {@link Aggregation}.
* @return
* @since 1.6
*/
public Aggregation withOptions(AggregationOptions options) {
@@ -181,13 +192,12 @@ public class Aggregation {
/**
* Creates a new {@link Aggregation} from the given {@link AggregationOperation}s.
*
* @param aggregationOperations must not be {@literal null} or empty.
* @param aggregationOperations must not be {@literal null}.
* @param options must not be {@literal null} or empty.
*/
protected Aggregation(List<AggregationOperation> aggregationOperations, AggregationOptions options) {
Assert.notNull(aggregationOperations, "AggregationOperations must not be null!");
Assert.isTrue(!aggregationOperations.isEmpty(), "At least one AggregationOperation has to be provided");
Assert.notNull(options, "AggregationOptions must not be null!");
// check $out is the last operation if it exists
@@ -228,7 +238,7 @@ public class Aggregation {
* Creates a new {@link ProjectionOperation} including the given fields.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link ProjectionOperation}.
* @return
*/
public static ProjectionOperation project(String... fields) {
return project(fields(fields));
@@ -238,7 +248,7 @@ public class Aggregation {
* Creates a new {@link ProjectionOperation} including the given {@link Fields}.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link ProjectionOperation}.
* @return
*/
public static ProjectionOperation project(Fields fields) {
return new ProjectionOperation(fields);
@@ -261,7 +271,7 @@ public class Aggregation {
* Factory method to create a new {@link UnwindOperation} for the field with the given name.
*
* @param field must not be {@literal null} or empty.
* @return new instance of {@link UnwindOperation}.
* @return
*/
public static UnwindOperation unwind(String field) {
return new UnwindOperation(field(field));
@@ -271,7 +281,7 @@ public class Aggregation {
* Factory method to create a new {@link ReplaceRootOperation} for the field with the given name.
*
* @param fieldName must not be {@literal null} or empty.
* @return new instance of {@link ReplaceRootOperation}.
* @return
* @since 1.10
*/
public static ReplaceRootOperation replaceRoot(String fieldName) {
@@ -283,7 +293,7 @@ public class Aggregation {
* {@link AggregationExpression}.
*
* @param aggregationExpression must not be {@literal null}.
* @return new instance of {@link ReplaceRootOperation}.
* @return
* @since 1.10
*/
public static ReplaceRootOperation replaceRoot(AggregationExpression aggregationExpression) {
@@ -349,7 +359,7 @@ public class Aggregation {
* Creates a new {@link GroupOperation} for the given fields.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link GroupOperation}.
* @return
*/
public static GroupOperation group(String... fields) {
return group(fields(fields));
@@ -370,7 +380,7 @@ public class Aggregation {
* {@link GraphLookupOperation} given {@literal fromCollection}.
*
* @param fromCollection must not be {@literal null} or empty.
* @return new instance of {@link StartWithBuilder} for creating a {@link GraphLookupOperation}.
* @return
* @since 1.10
*/
public static StartWithBuilder graphLookup(String fromCollection) {
@@ -381,7 +391,7 @@ public class Aggregation {
* Factory method to create a new {@link SortOperation} for the given {@link Sort}.
*
* @param sort must not be {@literal null}.
* @return new instance of {@link SortOperation}.
* @return
*/
public static SortOperation sort(Sort sort) {
return new SortOperation(sort);
@@ -392,7 +402,7 @@ public class Aggregation {
*
* @param direction must not be {@literal null}.
* @param fields must not be {@literal null}.
* @return new instance of {@link SortOperation}.
* @return
*/
public static SortOperation sort(Direction direction, String... fields) {
return new SortOperation(Sort.by(direction, fields));
@@ -402,7 +412,7 @@ public class Aggregation {
* Creates a new {@link SortByCountOperation} given {@literal groupByField}.
*
* @param field must not be {@literal null} or empty.
* @return new instance of {@link SortByCountOperation}.
* @return
* @since 2.1
*/
public static SortByCountOperation sortByCount(String field) {
@@ -413,7 +423,7 @@ public class Aggregation {
* Creates a new {@link SortByCountOperation} given {@link AggregationExpression group and sort expression}.
*
* @param groupAndSortExpression must not be {@literal null}.
* @return new instance of {@link SortByCountOperation}.
* @return
* @since 2.1
*/
public static SortByCountOperation sortByCount(AggregationExpression groupAndSortExpression) {
@@ -424,10 +434,9 @@ public class Aggregation {
* Creates a new {@link SkipOperation} skipping the given number of elements.
*
* @param elementsToSkip must not be less than zero.
* @return new instance of {@link SkipOperation}.
* @return
* @deprecated prepare to get this one removed in favor of {@link #skip(long)}.
*/
@Deprecated
public static SkipOperation skip(int elementsToSkip) {
return new SkipOperation(elementsToSkip);
}
@@ -436,7 +445,7 @@ public class Aggregation {
* Creates a new {@link SkipOperation} skipping the given number of elements.
*
* @param elementsToSkip must not be less than zero.
* @return new instance of {@link SkipOperation}.
* @return
*/
public static SkipOperation skip(long elementsToSkip) {
return new SkipOperation(elementsToSkip);
@@ -446,7 +455,7 @@ public class Aggregation {
* Creates a new {@link LimitOperation} limiting the result to the given number of elements.
*
* @param maxElements must not be less than zero.
* @return new instance of {@link LimitOperation}.
* @return
*/
public static LimitOperation limit(long maxElements) {
return new LimitOperation(maxElements);
@@ -456,7 +465,7 @@ public class Aggregation {
* Creates a new {@link SampleOperation} to select the specified number of documents from its input randomly.
*
* @param sampleSize must not be less than zero.
* @return new instance of {@link SampleOperation}.
* @return
* @since 2.0
*/
public static SampleOperation sample(long sampleSize) {
@@ -467,7 +476,7 @@ public class Aggregation {
* Creates a new {@link MatchOperation} using the given {@link Criteria}.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link MatchOperation}.
* @return
*/
public static MatchOperation match(Criteria criteria) {
return new MatchOperation(criteria);
@@ -477,7 +486,7 @@ public class Aggregation {
* Creates a new {@link MatchOperation} using the given {@link CriteriaDefinition}.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link MatchOperation}.
* @return
* @since 1.10
*/
public static MatchOperation match(CriteriaDefinition criteria) {
@@ -492,7 +501,7 @@ public class Aggregation {
* collection in the current database if one does not already exist. The collection is not visible until the
* aggregation completes. If the aggregation fails, MongoDB does not create the collection. Must not be
* {@literal null}.
* @return new instance of {@link OutOperation}.
* @return
*/
public static OutOperation out(String outCollectionName) {
return new OutOperation(outCollectionName);
@@ -502,7 +511,7 @@ public class Aggregation {
* Creates a new {@link BucketOperation} given {@literal groupByField}.
*
* @param groupByField must not be {@literal null} or empty.
* @return new instance of {@link BucketOperation}.
* @return
* @since 1.10
*/
public static BucketOperation bucket(String groupByField) {
@@ -513,7 +522,7 @@ public class Aggregation {
* Creates a new {@link BucketOperation} given {@link AggregationExpression group-by expression}.
*
* @param groupByExpression must not be {@literal null}.
* @return new instance of {@link BucketOperation}.
* @return
* @since 1.10
*/
public static BucketOperation bucket(AggregationExpression groupByExpression) {
@@ -525,7 +534,7 @@ public class Aggregation {
*
* @param groupByField must not be {@literal null} or empty.
* @param buckets number of buckets, must be a positive integer.
* @return new instance of {@link BucketAutoOperation}.
* @return
* @since 1.10
*/
public static BucketAutoOperation bucketAuto(String groupByField, int buckets) {
@@ -537,7 +546,7 @@ public class Aggregation {
*
* @param groupByExpression must not be {@literal null}.
* @param buckets number of buckets, must be a positive integer.
* @return new instance of {@link BucketAutoOperation}.
* @return
* @since 1.10
*/
public static BucketAutoOperation bucketAuto(AggregationExpression groupByExpression, int buckets) {
@@ -547,7 +556,7 @@ public class Aggregation {
/**
* Creates a new {@link FacetOperation}.
*
* @return new instance of {@link FacetOperation}.
* @return
* @since 1.10
*/
public static FacetOperation facet() {
@@ -558,7 +567,7 @@ public class Aggregation {
* Creates a new {@link FacetOperationBuilder} given {@link Aggregation}.
*
* @param aggregationOperations the sub-pipeline, must not be {@literal null}.
* @return new instance of {@link FacetOperation}.
* @return
* @since 1.10
*/
public static FacetOperationBuilder facet(AggregationOperation... aggregationOperations) {
@@ -607,7 +616,7 @@ public class Aggregation {
* Creates a new {@link Fields} instance for the given field names.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link Fields}.
* @return
* @see Fields#fields(String...)
*/
public static Fields fields(String... fields) {
@@ -619,7 +628,7 @@ public class Aggregation {
*
* @param name must not be {@literal null} or empty.
* @param target must not be {@literal null} or empty.
* @return new instance of {@link Fields}.
* @return
*/
public static Fields bind(String name, String target) {
return Fields.from(field(name, target));
@@ -641,7 +650,7 @@ public class Aggregation {
/**
* Returns a new {@link AggregationOptions.Builder}.
*
* @return new instance of {@link AggregationOptions.Builder}.
* @return
* @since 1.6
*/
public static AggregationOptions.Builder newAggregationOptions() {
@@ -703,7 +712,7 @@ public class Aggregation {
* otherwise.
*
* @param fieldRef may be {@literal null}.
* @return {@literal true} if the given field refers to a {@link SystemVariable}.
* @return
*/
public static boolean isReferingToSystemVariable(@Nullable String fieldRef) {

View File

@@ -31,8 +31,8 @@ public interface AggregationExpression {
* Turns the {@link AggregationExpression} into a {@link Document} within the given
* {@link AggregationOperationContext}.
*
* @param context must not be {@literal null}.
* @return the MongoDB native ({@link Document}) form of the expression.
* @param context
* @return
*/
Document toDocument(AggregationOperationContext context);
}

View File

@@ -53,7 +53,7 @@ interface AggregationExpressionTransformer
* @param currentNode must not be {@literal null}.
* @param parentNode may be {@literal null}.
* @param previousOperationObject may be {@literal null}.
* @param context must not be {@literal null}.
* @param aggregationContext must not be {@literal null}.
*/
public AggregationExpressionTransformationContext(T currentNode, @Nullable ExpressionNode parentNode,
@Nullable Document previousOperationObject, AggregationOperationContext context) {
@@ -67,7 +67,7 @@ interface AggregationExpressionTransformer
/**
* Returns the underlying {@link AggregationOperationContext}.
*
* @return never {@literal null}.
* @return
*/
public AggregationOperationContext getAggregationContext() {
return aggregationContext;
@@ -76,7 +76,7 @@ interface AggregationExpressionTransformer
/**
* Returns the {@link FieldReference} for the current {@link ExpressionNode}.
*
* @return never {@literal null}.
* @return
*/
public FieldReference getFieldReference() {
return aggregationContext.getReference(getCurrentNode().getName());

View File

@@ -41,7 +41,7 @@ public enum AggregationFunctionExpressions {
* Returns an {@link AggregationExpression} build from the current {@link Enum} name and the given parameters.
*
* @param parameters must not be {@literal null}
* @return new instance of {@link AggregationExpression}.
* @return
*/
public AggregationExpression of(Object... parameters) {

View File

@@ -58,20 +58,20 @@ public interface AggregationOperationContext {
Document getMappedObject(Document document, @Nullable Class<?> type);
/**
* Returns a {@link FieldReference} for the given field.
* Returns a {@link FieldReference} for the given field or {@literal null} if the context does not expose the given
* field.
*
* @param field must not be {@literal null}.
* @return the {@link FieldReference} for the given {@link Field}.
* @throws IllegalArgumentException if the context does not expose a field with the given name
* @return
*/
FieldReference getReference(Field field);
/**
* Returns the {@link FieldReference} for the field with the given name.
* Returns the {@link FieldReference} for the field with the given name or {@literal null} if the context does not
* expose a field with the given name.
*
* @param name must not be {@literal null} or empty.
* @return the {@link FieldReference} for the field with given {@literal name}.
* @throws IllegalArgumentException if the context does not expose a field with the given name
* @return
*/
FieldReference getReference(String name);

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import java.time.Duration;
import java.util.Optional;
import org.bson.Document;
@@ -45,12 +46,14 @@ public class AggregationOptions {
private static final String ALLOW_DISK_USE = "allowDiskUse";
private static final String COLLATION = "collation";
private static final String COMMENT = "comment";
private static final String MAX_TIME = "maxTimeMS";
private final boolean allowDiskUse;
private final boolean explain;
private final Optional<Document> cursor;
private final Optional<Collation> collation;
private final Optional<String> comment;
private Duration maxTime = Duration.ZERO;
/**
* Creates a new {@link AggregationOptions}.
@@ -129,7 +132,11 @@ public class AggregationOptions {
: null;
String comment = document.getString(COMMENT);
return new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
if (document.containsKey(MAX_TIME)) {
options.maxTime = Duration.ofMillis(document.getLong(MAX_TIME));
}
return options;
}
/**
@@ -146,7 +153,7 @@ public class AggregationOptions {
* Enables writing to temporary files. When set to true, aggregation stages can write data to the _tmp subdirectory in
* the dbPath directory.
*
* @return {@literal true} if enabled.
* @return
*/
public boolean isAllowDiskUse() {
return allowDiskUse;
@@ -155,7 +162,7 @@ public class AggregationOptions {
/**
* Specifies to return the information on the processing of the pipeline.
*
* @return {@literal true} if enabled.
* @return
*/
public boolean isExplain() {
return explain;
@@ -180,7 +187,7 @@ public class AggregationOptions {
/**
* Specify a document that contains options that control the creation of the cursor object.
*
* @return never {@literal null}.
* @return
*/
public Optional<Document> getCursor() {
return cursor;
@@ -189,7 +196,7 @@ public class AggregationOptions {
/**
* Get collation settings for string comparison.
*
* @return never {@literal null}.
* @return
* @since 2.0
*/
public Optional<Collation> getCollation() {
@@ -199,13 +206,21 @@ public class AggregationOptions {
/**
* Get the comment for the aggregation.
*
* @return never {@literal null}.
* @return
* @since 2.2
*/
public Optional<String> getComment() {
return comment;
}
/**
* @return the time limit for processing. {@link Duration#ZERO} is used for the default unbounded behavior.
* @since 3.0
*/
public Duration getMaxTime() {
return maxTime;
}
/**
* Returns a new potentially adjusted copy for the given {@code aggregationCommandObject} with the configuration
* applied.
@@ -233,13 +248,17 @@ public class AggregationOptions {
collation.map(Collation::toDocument).ifPresent(val -> result.append(COLLATION, val));
}
if (hasExecutionTimeLimit() && !result.containsKey(MAX_TIME)) {
result.append(MAX_TIME, maxTime.toMillis());
}
return result;
}
/**
* Returns a {@link Document} representation of this {@link AggregationOptions}.
*
* @return never {@literal null}.
* @return
*/
public Document toDocument() {
@@ -251,9 +270,21 @@ public class AggregationOptions {
collation.ifPresent(val -> document.append(COLLATION, val.toDocument()));
comment.ifPresent(val -> document.append(COMMENT, val));
if (hasExecutionTimeLimit()) {
document.append(MAX_TIME, maxTime.toMillis());
}
return document;
}
/**
* @return
* @since 3.0
*/
public boolean hasExecutionTimeLimit() {
return !maxTime.isZero() && !maxTime.isNegative();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@@ -279,12 +310,13 @@ public class AggregationOptions {
private @Nullable Document cursor;
private @Nullable Collation collation;
private @Nullable String comment;
private @Nullable Duration maxTime;
/**
* Defines whether to off-load intensive sort-operations to disk.
*
* @param allowDiskUse use {@literal true} to allow disk use during the aggregation.
* @return this.
* @param allowDiskUse
* @return
*/
public Builder allowDiskUse(boolean allowDiskUse) {
@@ -295,8 +327,8 @@ public class AggregationOptions {
/**
* Defines whether to get the execution plan for the aggregation instead of the actual results.
*
* @param explain use {@literal true} to enable explain feature.
* @return this.
* @param explain
* @return
*/
public Builder explain(boolean explain) {
@@ -307,8 +339,8 @@ public class AggregationOptions {
/**
* Additional options to the aggregation.
*
* @param cursor must not be {@literal null}.
* @return this.
* @param cursor
* @return
*/
public Builder cursor(Document cursor) {
@@ -319,8 +351,8 @@ public class AggregationOptions {
/**
* Define the initial cursor batch size.
*
* @param batchSize use a positive int.
* @return this.
* @param batchSize
* @return
* @since 2.0
*/
public Builder cursorBatchSize(int batchSize) {
@@ -333,7 +365,7 @@ public class AggregationOptions {
* Define collation settings for string comparison.
*
* @param collation can be {@literal null}.
* @return this.
* @return
* @since 2.0
*/
public Builder collation(@Nullable Collation collation) {
@@ -346,7 +378,7 @@ public class AggregationOptions {
* Define a comment to describe the execution.
*
* @param comment can be {@literal null}.
* @return this.
* @return
* @since 2.2
*/
public Builder comment(@Nullable String comment) {
@@ -355,13 +387,33 @@ public class AggregationOptions {
return this;
}
/**
* Set the time limit for processing.
*
* @param maxTime {@link Duration#ZERO} is used for the default unbounded behavior. {@link Duration#isNegative()
* Negative} values will be ignored.
* @return this.
* @since 3.0
*/
public Builder maxTime(@Nullable Duration maxTime) {
this.maxTime = maxTime;
return this;
}
/**
* Returns a new {@link AggregationOptions} instance with the given configuration.
*
* @return new instance of {@link AggregationOptions}.
* @return
*/
public AggregationOptions build() {
return new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
if (maxTime != null) {
options.maxTime = maxTime;
}
return options;
}
}
}

View File

@@ -59,7 +59,7 @@ public class AggregationResults<T> implements Iterable<T> {
/**
* Returns the aggregation results.
*
* @return the list of already mapped results or an empty one if none found.
* @return
*/
public List<T> getMappedResults() {
return mappedResults;
@@ -68,7 +68,7 @@ public class AggregationResults<T> implements Iterable<T> {
/**
* Returns the unique mapped result. Assumes no result or exactly one.
*
* @return the single already mapped result object or raise an error if more than one found.
* @return
* @throws IllegalArgumentException in case more than one result is available.
*/
@Nullable
@@ -88,7 +88,7 @@ public class AggregationResults<T> implements Iterable<T> {
/**
* Returns the server that has been used to perform the aggregation.
*
* @return can be {@literal null}.
* @return
*/
@Nullable
public String getServerUsed() {
@@ -98,7 +98,7 @@ public class AggregationResults<T> implements Iterable<T> {
/**
* Returns the raw result that was returned by the server.
*
* @return the raw response.
* @return
* @since 1.6
*/
public Document getRawResults() {

View File

@@ -56,7 +56,7 @@ public class AggregationSpELExpression implements AggregationExpression {
*
* @param expressionString must not be {@literal null}.
* @param parameters can be empty.
* @return new instance of {@link AggregationSpELExpression}.
* @return
*/
public static AggregationSpELExpression expressionOf(String expressionString, Object... parameters) {

View File

@@ -0,0 +1,325 @@
/*
* Copyright 2019-2020 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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.SerializationUtils;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Abstraction for {@code db.collection.update()} using an aggregation pipeline. Aggregation pipeline updates use a more
* expressive update statement expressing conditional updates based on current field values or updating one field using
* the value of another field(s).
*
* <pre class="code">
* AggregationUpdate update = AggregationUpdate.update().set("average")
* .toValue(ArithmeticOperators.valueOf("tests").avg()).set("grade")
* .toValue(ConditionalOperators
* .switchCases(CaseOperator.when(Gte.valueOf("average").greaterThanEqualToValue(90)).then("A"),
* CaseOperator.when(Gte.valueOf("average").greaterThanEqualToValue(80)).then("B"),
* CaseOperator.when(Gte.valueOf("average").greaterThanEqualToValue(70)).then("C"),
* CaseOperator.when(Gte.valueOf("average").greaterThanEqualToValue(60)).then("D"))
* .defaultTo("F"));
* </pre>
*
* The above sample is equivalent to the JSON update statement:
*
* <pre class="code">
* db.collection.update(
* { },
* [
* { $set: { average : { $avg: "$tests" } } },
* { $set: { grade: { $switch: {
* branches: [
* { case: { $gte: [ "$average", 90 ] }, then: "A" },
* { case: { $gte: [ "$average", 80 ] }, then: "B" },
* { case: { $gte: [ "$average", 70 ] }, then: "C" },
* { case: { $gte: [ "$average", 60 ] }, then: "D" }
* ],
* default: "F"
* } } } }
* ],
* { multi: true }
* )
* </pre>
*
* @author Christoph Strobl
* @author Mark Paluch
* @see <a href=
* "https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-with-aggregation-pipeline">MongoDB
* Reference Documentation</a>
* @since 3.0
*/
public class AggregationUpdate extends Aggregation implements UpdateDefinition {
private boolean isolated = false;
private Set<String> keysTouched = new HashSet<>();
/**
* Create new {@link AggregationUpdate}.
*/
protected AggregationUpdate() {
this(new ArrayList<>());
}
/**
* Create new {@link AggregationUpdate} with the given aggregation pipeline to apply.
*
* @param pipeline must not be {@literal null}.
*/
protected AggregationUpdate(List<AggregationOperation> pipeline) {
super(pipeline);
for (AggregationOperation operation : pipeline) {
if (operation instanceof FieldsExposingAggregationOperation) {
((FieldsExposingAggregationOperation) operation).getFields().forEach(it -> {
keysTouched.add(it.getName());
});
}
}
}
/**
* Start defining the update pipeline to execute.
*
* @return new instance of {@link AggregationUpdate}.
*/
public static AggregationUpdate update() {
return new AggregationUpdate();
}
/**
* Create a new AggregationUpdate from the given {@link AggregationOperation}s.
*
* @return new instance of {@link AggregationUpdate}.
*/
public static AggregationUpdate from(List<AggregationOperation> pipeline) {
return new AggregationUpdate(pipeline);
}
/**
* Adds new fields to documents. {@code $set} outputs documents that contain all existing fields from the input
* documents and newly added fields.
*
* @param setOperation must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/set/">$set Aggregation Reference</a>
*/
public AggregationUpdate set(SetOperation setOperation) {
Assert.notNull(setOperation, "SetOperation must not be null!");
setOperation.getFields().forEach(it -> {
keysTouched.add(it.getName());
});
operations.add(setOperation);
return this;
}
/**
* {@code $unset} removes/excludes fields from documents.
*
* @param unsetOperation must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unset/">$unset Aggregation
* Reference</a>
*/
public AggregationUpdate unset(UnsetOperation unsetOperation) {
Assert.notNull(unsetOperation, "UnsetOperation must not be null!");
operations.add(unsetOperation);
keysTouched.addAll(unsetOperation.removedFieldNames());
return this;
}
/**
* {@code $replaceWith} replaces the input document with the specified document. The operation replaces all existing
* fields in the input document, including the <strong>_id</strong> field.
*
* @param replaceWithOperation
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/replaceWith/">$replaceWith Aggregation
* Reference</a>
*/
public AggregationUpdate replaceWith(ReplaceWithOperation replaceWithOperation) {
Assert.notNull(replaceWithOperation, "ReplaceWithOperation must not be null!");
operations.add(replaceWithOperation);
return this;
}
/**
* {@code $replaceWith} replaces the input document with the value.
*
* @param value must not be {@literal null}.
* @return this.
*/
public AggregationUpdate replaceWith(Object value) {
Assert.notNull(value, "Value must not be null!");
return replaceWith(ReplaceWithOperation.replaceWithValue(value));
}
/**
* Fluent API variant for {@code $set} adding a single {@link SetOperation pipeline operation} every time. To update
* multiple fields within one {@link SetOperation} use {@link #set(SetOperation)}.
*
* @param key must not be {@literal null}.
* @return new instance of {@link SetValueAppender}.
* @see #set(SetOperation)
*/
public SetValueAppender set(String key) {
Assert.notNull(key, "Key must not be null!");
return new SetValueAppender() {
@Override
public AggregationUpdate toValue(@Nullable Object value) {
return set(SetOperation.builder().set(key).toValue(value));
}
@Override
public AggregationUpdate toValueOf(Object value) {
Assert.notNull(value, "Value must not be null!");
return set(SetOperation.builder().set(key).toValueOf(value));
}
};
}
/**
* Short for {@link #unset(UnsetOperation)}.
*
* @param keys
* @return
*/
public AggregationUpdate unset(String... keys) {
Assert.notNull(keys, "Keys must not be null!");
Assert.noNullElements(keys, "Keys must not contain null elements.");
return unset(new UnsetOperation(Arrays.stream(keys).map(Fields::field).collect(Collectors.toList())));
}
/**
* Prevents a write operation that affects <strong>multiple</strong> documents from yielding to other reads or writes
* once the first document is written. <br />
* Use with {@link org.springframework.data.mongodb.core.MongoOperations#updateMulti(Query, UpdateDefinition, Class)}.
*
* @return never {@literal null}.
*/
public AggregationUpdate isolated() {
isolated = true;
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.UpdateDefinition#isIsolated()
*/
@Override
public Boolean isIsolated() {
return isolated;
}
/*
* Returns a update document containing the update pipeline.
* The resulting document needs to be unwrapped to be used with update operations.
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.UpdateDefinition#getUpdateObject()
*/
@Override
public Document getUpdateObject() {
return new Document("", toPipeline(Aggregation.DEFAULT_CONTEXT));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.UpdateDefinition#modifies(java.lang.String)
*/
@Override
public boolean modifies(String key) {
return keysTouched.contains(key);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.UpdateDefinition#inc(java.lang.String)
*/
@Override
public void inc(String key) {
set(new SetOperation(key, ArithmeticOperators.valueOf(key).add(1)));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.UpdateDefinition#getArrayFilters()
*/
@Override
public List<ArrayFilter> getArrayFilters() {
return Collections.emptyList();
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(",\n", "[\n", "\n]");
toPipeline(Aggregation.DEFAULT_CONTEXT).stream().map(SerializationUtils::serializeToJsonSafely)
.forEach(joiner::add);
return joiner.toString();
}
/**
* Fluent API AggregationUpdate builder.
*
* @author Christoph Strobl
*/
public interface SetValueAppender {
/**
* Define the target value as is.
*
* @param value can be {@literal null}.
* @return never {@literal null}.
*/
AggregationUpdate toValue(@Nullable Object value);
/**
* Define the target value as value, an {@link AggregationExpression} or a {@link Field} reference.
*
* @param value can be {@literal null}.
* @return never {@literal null}.
*/
AggregationUpdate toValueOf(Object value);
}
}

View File

@@ -32,9 +32,9 @@ interface AggregationUtils {
* Converts the given {@link Range} into an array of values.
*
* @param range must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
static List<Long> toRangeValues(Range<Long> range) {
public static List<Long> toRangeValues(Range<Long> range) {
Assert.notNull(range, "Range must not be null!");

View File

@@ -43,7 +43,7 @@ public class ArrayOperators {
* Take the array referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ArrayOperatorFactory}.
* @return
*/
public static ArrayOperatorFactory arrayOf(String fieldReference) {
return new ArrayOperatorFactory(fieldReference);
@@ -53,7 +53,7 @@ public class ArrayOperators {
* Take the array referenced resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ArrayOperatorFactory}.
* @return
*/
public static ArrayOperatorFactory arrayOf(AggregationExpression expression) {
return new ArrayOperatorFactory(expression);
@@ -123,8 +123,8 @@ public class ArrayOperators {
* Creates new {@link AggregationExpression} that takes the associated array and returns the element at the
* specified array {@literal position}.
*
* @param position the element index.
* @return new instance of {@link ArrayElemAt}.
* @param position
* @return
*/
public ArrayElemAt elementAt(int position) {
return createArrayElemAt().elementAt(position);
@@ -135,7 +135,7 @@ public class ArrayOperators {
* resulting form the given {@literal expression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ArrayElemAt}.
* @return
*/
public ArrayElemAt elementAt(AggregationExpression expression) {
@@ -148,7 +148,7 @@ public class ArrayOperators {
* defined by the referenced {@literal field}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ArrayElemAt}.
* @return
*/
public ArrayElemAt elementAt(String fieldReference) {
@@ -170,7 +170,7 @@ public class ArrayOperators {
* {@literal arrayFieldReference} to it.
*
* @param arrayFieldReference must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
* @return
*/
public ConcatArrays concat(String arrayFieldReference) {
@@ -183,7 +183,7 @@ public class ArrayOperators {
* the given {@literal expression} to it.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
* @return
*/
public ConcatArrays concat(AggregationExpression expression) {
@@ -204,7 +204,7 @@ public class ArrayOperators {
* Creates new {@link AggregationExpression} that takes the associated array and selects a subset of the array to
* return based on the specified condition.
*
* @return new instance of {@link AsBuilder} to create a {@link Filter}.
* @return
*/
public AsBuilder filter() {
@@ -219,7 +219,7 @@ public class ArrayOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated array and an check if its an array.
*
* @return new instance of {@link IsArray}.
* @return
*/
public IsArray isArray() {
@@ -231,7 +231,7 @@ public class ArrayOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated array and retrieves its length.
*
* @return new instance of {@link Size}.
* @return
*/
public Size length() {
@@ -245,7 +245,7 @@ public class ArrayOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated array and selects a subset from it.
*
* @return new instance of {@link Slice}.
* @return
*/
public Slice slice() {
@@ -261,7 +261,7 @@ public class ArrayOperators {
* value and returns the array index (zero-based) of the first occurrence.
*
* @param value must not be {@literal null}.
* @return new instance of {@link IndexOfArray}.
* @return
*/
public IndexOfArray indexOf(Object value) {
@@ -276,7 +276,7 @@ public class ArrayOperators {
/**
* Creates new {@link AggregationExpression} that returns an array with the elements in reverse order.
*
* @return new instance of {@link ReverseArray}.
* @return
*/
public ReverseArray reverse() {
@@ -293,7 +293,7 @@ public class ArrayOperators {
* an array and combines them into a single value.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ReduceInitialValueBuilder} to create {@link Reduce}.
* @return
*/
public ArrayOperatorFactory.ReduceInitialValueBuilder reduce(AggregationExpression expression) {
@@ -305,8 +305,8 @@ public class ArrayOperators {
* Start creating new {@link AggregationExpression} that applies an {@link AggregationExpression} to each element in
* an array and combines them into a single value.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link ReduceInitialValueBuilder} to create {@link Reduce}.
* @param expressions
* @return
*/
public ArrayOperatorFactory.ReduceInitialValueBuilder reduce(PropertyExpression... expressions) {
@@ -320,7 +320,7 @@ public class ArrayOperators {
* the second input array, etc.
*
* @param arrays must not be {@literal null}.
* @return new instance of {@link Zip}.
* @return
*/
public Zip zipWith(Object... arrays) {
@@ -336,7 +336,7 @@ public class ArrayOperators {
* associated array.
*
* @param value must not be {@literal null}.
* @return new instance of {@link In}.
* @return
*/
public In containsValue(Object value) {
@@ -413,7 +413,7 @@ public class ArrayOperators {
* Creates new {@link ArrayElemAt}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ArrayElemAt}.
* @return
*/
public static ArrayElemAt arrayOf(String fieldReference) {
@@ -425,7 +425,7 @@ public class ArrayOperators {
* Creates new {@link ArrayElemAt}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ArrayElemAt}.
* @return
*/
public static ArrayElemAt arrayOf(AggregationExpression expression) {
@@ -446,34 +446,16 @@ public class ArrayOperators {
return new ArrayElemAt(Collections.singletonList(values));
}
/**
* Use the element with given index number.
*
* @param index the index number
* @return new instance of {@link ArrayElemAt}.
*/
public ArrayElemAt elementAt(int index) {
return new ArrayElemAt(append(index));
}
/**
* Use the element at the index number evaluated from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ArrayElemAt}.
*/
public ArrayElemAt elementAt(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new ArrayElemAt(append(expression));
}
/**
* Use the element at the index number traken from the given field.
*
* @param arrayFieldReference the field name.
* @return new instance of {@link ArrayElemAt}.
*/
public ArrayElemAt elementAt(String arrayFieldReference) {
Assert.notNull(arrayFieldReference, "ArrayReference must not be null!");
@@ -501,7 +483,7 @@ public class ArrayOperators {
* Creates new {@link ConcatArrays}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
* @return
*/
public static ConcatArrays arrayOf(String fieldReference) {
@@ -513,7 +495,7 @@ public class ArrayOperators {
* Creates new {@link ConcatArrays}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
* @return
*/
public static ConcatArrays arrayOf(AggregationExpression expression) {
@@ -534,24 +516,12 @@ public class ArrayOperators {
return new ConcatArrays(Collections.singletonList(values));
}
/**
* Concat with the array stored at the given field.
*
* @param arrayFieldReference must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
*/
public ConcatArrays concat(String arrayFieldReference) {
Assert.notNull(arrayFieldReference, "ArrayFieldReference must not be null!");
return new ConcatArrays(append(Fields.field(arrayFieldReference)));
}
/**
* Concat with the array resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ConcatArrays}.
*/
public ConcatArrays concat(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
@@ -604,7 +574,7 @@ public class ArrayOperators {
* Set the {@literal values} to apply the {@code $filter} to.
*
* @param values must not be {@literal null}.
* @return new instance of {@link AsBuilder} to create the {@link Filter}.
* @return
*/
public static AsBuilder filter(List<?> values) {
@@ -681,7 +651,7 @@ public class ArrayOperators {
* Set the {@literal variableName} for the elements in the input array.
*
* @param variableName must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
ConditionBuilder as(String variableName);
}
@@ -695,7 +665,7 @@ public class ArrayOperators {
* Set the {@link AggregationExpression} that determines whether to include the element in the resulting array.
*
* @param expression must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
Filter by(AggregationExpression expression);
@@ -703,7 +673,7 @@ public class ArrayOperators {
* Set the {@literal expression} that determines whether to include the element in the resulting array.
*
* @param expression must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
Filter by(String expression);
@@ -711,7 +681,7 @@ public class ArrayOperators {
* Set the {@literal expression} that determines whether to include the element in the resulting array.
*
* @param expression must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
Filter by(Document expression);
}
@@ -730,7 +700,7 @@ public class ArrayOperators {
/**
* Creates new {@link InputBuilder}.
*
* @return new instance of {@link FilterExpressionBuilder}.
* @return
*/
public static InputBuilder newBuilder() {
return new FilterExpressionBuilder();
@@ -830,7 +800,7 @@ public class ArrayOperators {
* Creates new {@link IsArray}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IsArray}.
* @return
*/
public static IsArray isArray(String fieldReference) {
@@ -842,7 +812,7 @@ public class ArrayOperators {
* Creates new {@link IsArray}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IsArray}.
* @return
*/
public static IsArray isArray(AggregationExpression expression) {
@@ -871,7 +841,7 @@ public class ArrayOperators {
* Creates new {@link Size}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Size}.
* @return
*/
public static Size lengthOfArray(String fieldReference) {
@@ -883,7 +853,7 @@ public class ArrayOperators {
* Creates new {@link Size}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Size}.
* @return
*/
public static Size lengthOfArray(AggregationExpression expression) {
@@ -925,7 +895,7 @@ public class ArrayOperators {
* Creates new {@link Slice}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Slice}.
* @return
*/
public static Slice sliceArrayOf(String fieldReference) {
@@ -937,7 +907,7 @@ public class ArrayOperators {
* Creates new {@link Slice}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Slice}.
* @return
*/
public static Slice sliceArrayOf(AggregationExpression expression) {
@@ -958,22 +928,10 @@ public class ArrayOperators {
return new Slice(Collections.singletonList(values));
}
/**
* Slice the number of elements.
*
* @param nrElements elements to slice.
* @return new instance of {@link Slice}.
*/
public Slice itemCount(int nrElements) {
return new Slice(append(nrElements));
}
/**
* Slice using offset and count.
*
* @param position the start position
* @return new instance of {@link SliceElementsBuilder} to create {@link Slice}.
*/
public SliceElementsBuilder offset(final int position) {
return new SliceElementsBuilder() {
@@ -1020,7 +978,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IndexOfArray}.
* @return
*/
public static IndexOfArrayBuilder arrayOf(String fieldReference) {
@@ -1032,7 +990,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfArray}.
* @return
*/
public static IndexOfArrayBuilder arrayOf(AggregationExpression expression) {
@@ -1044,7 +1002,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param values must not be {@literal null}.
* @return new instance of {@link IndexOfArrayBuilder} to create {@link IndexOfArray}.
* @return new instance of {@link IndexOfArray}.
* @since 2.2
*/
public static IndexOfArrayBuilder arrayOf(Collection<?> values) {
@@ -1053,12 +1011,6 @@ public class ArrayOperators {
return new IndexOfArrayBuilder(values);
}
/**
* Lookup within a given range.
*
* @param range the lookup range.
* @return new instance of {@link IndexOfArray}.
*/
public IndexOfArray within(Range<Long> range) {
return new IndexOfArray(append(AggregationUtils.toRangeValues(range)));
}
@@ -1078,7 +1030,7 @@ public class ArrayOperators {
* Set the {@literal value} to check for its index in the array.
*
* @param value must not be {@literal null}.
* @return new instance of {@link IndexOfArray}.
* @return
*/
public IndexOfArray indexOf(Object value) {
@@ -1108,7 +1060,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link RangeOperatorBuilder} to create {@link RangeOperator}.
* @return
*/
public static RangeOperatorBuilder rangeStartingAt(String fieldReference) {
return new RangeOperatorBuilder(Fields.field(fieldReference));
@@ -1118,7 +1070,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link RangeOperatorBuilder} to create {@link RangeOperator}.
* @return
*/
public static RangeOperatorBuilder rangeStartingAt(AggregationExpression expression) {
return new RangeOperatorBuilder(expression);
@@ -1128,7 +1080,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param value
* @return new instance of {@link RangeOperator}.
* @return
*/
public static RangeOperatorBuilder rangeStartingAt(long value) {
return new RangeOperatorBuilder(value);
@@ -1150,7 +1102,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param index
* @return new instance of {@link RangeOperator}.
* @return
*/
public RangeOperator to(long index) {
return new RangeOperator(Arrays.asList(startPoint, index));
@@ -1160,7 +1112,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link RangeOperator}.
* @return
*/
public RangeOperator to(AggregationExpression expression) {
return new RangeOperator(Arrays.asList(startPoint, expression));
@@ -1170,7 +1122,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link RangeOperator}.
* @return
*/
public RangeOperator to(String fieldReference) {
return new RangeOperator(Arrays.asList(startPoint, Fields.field(fieldReference)));
@@ -1198,7 +1150,7 @@ public class ArrayOperators {
* Creates new {@link ReverseArray} given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ReverseArray}.
* @return
*/
public static ReverseArray reverseArrayOf(String fieldReference) {
return new ReverseArray(Fields.field(fieldReference));
@@ -1208,7 +1160,7 @@ public class ArrayOperators {
* Creates new {@link ReverseArray} given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ReverseArray}.
* @return
*/
public static ReverseArray reverseArrayOf(AggregationExpression expression) {
return new ReverseArray(expression);
@@ -1287,7 +1239,7 @@ public class ArrayOperators {
* Start creating new {@link Reduce}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link InitialValueBuilder} to create {@link Reduce}.
* @return
*/
public static InitialValueBuilder arrayOf(final String fieldReference) {
@@ -1326,7 +1278,7 @@ public class ArrayOperators {
* Start creating new {@link Reduce}.
*
* @param arrayValueExpression must not be {@literal null}.
* @return new instance of {@link InitialValueBuilder} to create {@link Reduce}.
* @return
*/
public static InitialValueBuilder arrayOf(final AggregationExpression arrayValueExpression) {
@@ -1366,7 +1318,7 @@ public class ArrayOperators {
* Define the initial cumulative value set before in is applied to the first element of the input array.
*
* @param initialValue must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
ReduceBuilder withInitialValue(Object initialValue);
}
@@ -1383,7 +1335,7 @@ public class ArrayOperators {
* {@link Variable#VALUE} are available.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Reduce}.
* @return
*/
Reduce reduce(AggregationExpression expression);
@@ -1394,7 +1346,7 @@ public class ArrayOperators {
* {@link Variable#VALUE} are available.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link Reduce}.
* @return
*/
Reduce reduce(PropertyExpression... expressions);
}
@@ -1420,7 +1372,7 @@ public class ArrayOperators {
* Define a result property for an {@link AggregationExpression} used in {@link Reduce}.
*
* @param name must not be {@literal null}.
* @return new instance of {@link AsBuilder} to create {@link Reduce}.
* @return
*/
public static AsBuilder property(final String name) {
@@ -1450,7 +1402,7 @@ public class ArrayOperators {
* Set the {@link AggregationExpression} resulting in the properties value.
*
* @param expression must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
PropertyExpression definedAs(AggregationExpression expression);
}
@@ -1507,7 +1459,7 @@ public class ArrayOperators {
* eg. {@code $$value.product}
*
* @param property must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public Field referringTo(final String property) {
@@ -1556,7 +1508,7 @@ public class ArrayOperators {
* Start creating new {@link Zip}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ZipBuilder} to create {@link Zip}.
* @return
*/
public static ZipBuilder arrayOf(String fieldReference) {
@@ -1568,7 +1520,7 @@ public class ArrayOperators {
* Start creating new {@link Zip}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ZipBuilder} to create {@link Zip}.
* @return
*/
public static ZipBuilder arrayOf(AggregationExpression expression) {
@@ -1592,7 +1544,7 @@ public class ArrayOperators {
/**
* Create new {@link Zip} and set the {@code useLongestLength} property to {@literal true}.
*
* @return new instance of {@link Zip}.
* @return
*/
public Zip useLongestLength() {
return new Zip(append("useLongestLength", true));
@@ -1602,7 +1554,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Zip}.
* @return
*/
public Zip defaultTo(String fieldReference) {
@@ -1614,7 +1566,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Zip}.
* @return
*/
public Zip defaultTo(AggregationExpression expression) {
@@ -1626,7 +1578,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param array must not be {@literal null}.
* @return new instance of {@link Zip}.
* @return
*/
public Zip defaultTo(Object[] array) {
@@ -1650,7 +1602,7 @@ public class ArrayOperators {
* array, etc.
*
* @param arrays arrays to zip the referenced one with. must not be {@literal null}.
* @return new instance of {@link Zip}.
* @return
*/
public Zip zip(Object... arrays) {
@@ -1693,7 +1645,7 @@ public class ArrayOperators {
* Start creating {@link In}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link InBuilder} to create {@link In}.
* @return
*/
public static InBuilder arrayOf(String fieldReference) {
@@ -1710,7 +1662,7 @@ public class ArrayOperators {
* Start creating {@link In}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link InBuilder} to create {@link In}.
* @return
*/
public static InBuilder arrayOf(AggregationExpression expression) {
@@ -1752,7 +1704,7 @@ public class ArrayOperators {
* Set the {@literal value} to check for existence in the array.
*
* @param value must not be {@literal value}.
* @return new instance of {@link In}.
* @return
*/
In containsValue(Object value);
}

View File

@@ -34,7 +34,7 @@ public class BooleanOperators {
* Take the array referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link BooleanOperatorFactory}.
* @return
*/
public static BooleanOperatorFactory valueOf(String fieldReference) {
return new BooleanOperatorFactory(fieldReference);
@@ -44,7 +44,7 @@ public class BooleanOperators {
* Take the value resulting of the given {@link AggregationExpression}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link BooleanOperatorFactory}.
* @return
*/
public static BooleanOperatorFactory valueOf(AggregationExpression fieldReference) {
return new BooleanOperatorFactory(fieldReference);
@@ -55,7 +55,7 @@ public class BooleanOperators {
* opposite boolean value.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Not}.
* @return
*/
public static Not not(String fieldReference) {
return Not.not(fieldReference);
@@ -66,7 +66,7 @@ public class BooleanOperators {
* and returns the opposite boolean value.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Not}.
* @return
*/
public static Not not(AggregationExpression expression) {
return Not.not(expression);
@@ -109,7 +109,7 @@ public class BooleanOperators {
* all of the expressions are {@literal true}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link And}.
* @return
*/
public And and(AggregationExpression expression) {
@@ -122,7 +122,7 @@ public class BooleanOperators {
* all of the expressions are {@literal true}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link And}.
* @return
*/
public And and(String fieldReference) {
@@ -139,7 +139,7 @@ public class BooleanOperators {
* any of the expressions are {@literal true}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public Or or(AggregationExpression expression) {
@@ -152,7 +152,7 @@ public class BooleanOperators {
* any of the expressions are {@literal true}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public Or or(String fieldReference) {
@@ -167,7 +167,7 @@ public class BooleanOperators {
/**
* Creates new {@link AggregationExpression} that evaluates a boolean and returns the opposite boolean value.
*
* @return new instance of {@link Not}.
* @return
*/
public Not not() {
return usesFieldRef() ? Not.not(fieldReference) : Not.not(expression);
@@ -198,8 +198,8 @@ public class BooleanOperators {
* Creates new {@link And} that evaluates one or more expressions and returns {@literal true} if all of the
* expressions are {@literal true}.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link And}.
* @param expressions
* @return
*/
public static And and(Object... expressions) {
return new And(Arrays.asList(expressions));
@@ -209,7 +209,7 @@ public class BooleanOperators {
* Creates new {@link And} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link And}.
* @return
*/
public And andExpression(AggregationExpression expression) {
@@ -221,7 +221,7 @@ public class BooleanOperators {
* Creates new {@link And} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link And}.
* @return
*/
public And andField(String fieldReference) {
@@ -233,7 +233,7 @@ public class BooleanOperators {
* Creates new {@link And} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link And}.
* @return
*/
public And andValue(Object value) {
@@ -263,7 +263,7 @@ public class BooleanOperators {
* expressions are {@literal true}.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public static Or or(Object... expressions) {
@@ -275,7 +275,7 @@ public class BooleanOperators {
* Creates new {@link Or} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public Or orExpression(AggregationExpression expression) {
@@ -287,7 +287,7 @@ public class BooleanOperators {
* Creates new {@link Or} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public Or orField(String fieldReference) {
@@ -299,7 +299,7 @@ public class BooleanOperators {
* Creates new {@link Or} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Or}.
* @return
*/
public Or orValue(Object value) {
@@ -329,7 +329,7 @@ public class BooleanOperators {
* value.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Not}.
* @return
*/
public static Not not(String fieldReference) {
@@ -342,7 +342,7 @@ public class BooleanOperators {
* returns the opposite boolean value.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Not}.
* @return
*/
public static Not not(AggregationExpression expression) {

View File

@@ -15,12 +15,12 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.BucketAutoOperation.BucketAutoOperationOutputBuilder;
import org.springframework.data.mongodb.core.aggregation.BucketOperationSupport.OutputBuilder;
import org.springframework.util.Assert;
import org.bson.Document;
/**
* Encapsulates the aggregation framework {@code $bucketAuto}-operation. <br />
* Bucket stage is typically used with {@link Aggregation} and {@code $facet}. Categorizes incoming documents into a
@@ -113,7 +113,7 @@ public class BucketAutoOperation extends BucketOperationSupport<BucketAutoOperat
* Configures a number of bucket {@literal buckets} and return a new {@link BucketAutoOperation}.
*
* @param buckets must be a positive number.
* @return new instance of {@link BucketAutoOperation}.
* @return
*/
public BucketAutoOperation withBuckets(int buckets) {
@@ -128,7 +128,7 @@ public class BucketAutoOperation extends BucketOperationSupport<BucketAutoOperat
* Use either predefined {@link Granularities} or provide a own one.
*
* @param granularity must not be {@literal null}.
* @return new instance of {@link BucketAutoOperation}.
* @return
*/
public BucketAutoOperation withGranularity(Granularity granularity) {
@@ -209,7 +209,7 @@ public class BucketAutoOperation extends BucketOperationSupport<BucketAutoOperat
*
* @param expression must not be {@literal null}.
* @param operation must not be {@literal null}.
* @param parameters must not be {@literal null}.
* @param parameters
*/
protected ExpressionBucketAutoOperationBuilder(String expression, BucketAutoOperation operation,
Object[] parameters) {

View File

@@ -20,11 +20,11 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.BucketOperation.BucketOperationOutputBuilder;
import org.springframework.util.Assert;
import org.bson.Document;
/**
* Encapsulates the aggregation framework {@code $bucket}-operation. <br />
*
@@ -110,7 +110,7 @@ public class BucketOperation extends BucketOperationSupport<BucketOperation, Buc
* Configures a default bucket {@literal literal} and return a new {@link BucketOperation}.
*
* @param literal must not be {@literal null}.
* @return new instance of {@link BucketOperation}.
* @return
*/
public BucketOperation withDefaultBucket(Object literal) {
@@ -123,7 +123,7 @@ public class BucketOperation extends BucketOperationSupport<BucketOperation, Buc
* preserved and the new {@literal boundaries} are appended.
*
* @param boundaries must not be {@literal null}.
* @return new instance of {@link BucketOperation}.
* @return
*/
public BucketOperation withBoundaries(Object... boundaries) {
@@ -204,12 +204,12 @@ public class BucketOperation extends BucketOperationSupport<BucketOperation, Buc
extends ExpressionBucketOperationBuilderSupport<BucketOperationOutputBuilder, BucketOperation> {
/**
* Creates a new {@link ExpressionBucketOperationBuilderSupport} for the given value, {@link BucketOperation} and
* parameters.
* Creates a new {@link ExpressionBucketOperationBuilderSupport} for the given value, {@link BucketOperation}
* and parameters.
*
* @param expression must not be {@literal null}.
* @param operation must not be {@literal null}.
* @param parameters must not be {@literal null}.
* @param parameters
*/
protected ExpressionBucketOperationBuilder(String expression, BucketOperation operation, Object[] parameters) {
super(expression, operation, parameters);

View File

@@ -21,13 +21,14 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.BucketOperationSupport.OutputBuilder;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
import org.springframework.data.mongodb.core.aggregation.ProjectionOperation.ProjectionOperationBuilder;
import org.springframework.expression.spel.ast.Projection;
import org.springframework.util.Assert;
import org.bson.Document;
/**
* Base class for bucket operations that support output expressions the aggregation framework. <br />
* Bucket stages collect documents into buckets and can contribute output fields. <br />
@@ -103,7 +104,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
*
* @param expression the SpEL expression, must not be {@literal null} or empty.
* @param params must not be {@literal null}
* @return new instance of {@link ExpressionBucketOperationBuilderSupport} to create {@link BucketOperation}.
* @return
*/
public abstract ExpressionBucketOperationBuilderSupport<B, T> andOutputExpression(String expression,
Object... params);
@@ -113,7 +114,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* resulting bucket documents.
*
* @param expression the SpEL expression, must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
public abstract B andOutput(AggregationExpression expression);
@@ -123,14 +124,14 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* {@literal fieldName}.
*
* @param fieldName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
public abstract B andOutput(String fieldName);
/**
* Creates a new {@link BucketOperationSupport} given to add a count field to the resulting bucket documents.
*
* @return never {@literal null}.
* @return
*/
public B andOutputCount() {
return andOutput(new AggregationExpression() {
@@ -230,7 +231,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* Generates a builder for a {@code $sum}-expression. <br />
* Count expressions are emulated via {@code $sum: 1}.
*
* @return never {@literal null}.
* @return
*/
public B count() {
return sum(1);
@@ -239,7 +240,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $sum}-expression for the current value.
*
* @return never {@literal null}.
* @return
*/
public B sum() {
return apply(Accumulators.SUM);
@@ -248,8 +249,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $sum}-expression for the given {@literal value}.
*
* @param value must not be {@literal null}.
* @return never {@literal null}.
* @param value
* @return
*/
public B sum(Number value) {
return apply(new OperationOutput(Accumulators.SUM.getMongoOperator(), Collections.singleton(value)));
@@ -258,7 +259,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $last}-expression for the current value..
*
* @return never {@literal null}.
* @return
*/
public B last() {
return apply(Accumulators.LAST);
@@ -267,7 +268,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $first}-expression the current value.
*
* @return never {@literal null}.
* @return
*/
public B first() {
return apply(Accumulators.FIRST);
@@ -276,7 +277,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $avg}-expression for the current value.
*
* @return never {@literal null}.
* @param reference
* @return
*/
public B avg() {
return apply(Accumulators.AVG);
@@ -285,7 +287,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $min}-expression for the current value.
*
* @return never {@literal null}.
* @return
*/
public B min() {
return apply(Accumulators.MIN);
@@ -294,7 +296,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $max}-expression for the current value.
*
* @return never {@literal null}.
* @return
*/
public B max() {
return apply(Accumulators.MAX);
@@ -303,7 +305,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $push}-expression for the current value.
*
* @return never {@literal null}.
* @return
*/
public B push() {
return apply(Accumulators.PUSH);
@@ -312,7 +314,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $addToSet}-expression for the current value.
*
* @return never {@literal null}.
* @return
*/
public B addToSet() {
return apply(Accumulators.ADDTOSET);
@@ -323,7 +325,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
*
* @param operation the operation name, must not be {@literal null} or empty.
* @param values must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public B apply(String operation, Object... values) {
@@ -340,7 +342,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* Apply an {@link OperationOutput} to this output.
*
* @param operationOutput must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
protected abstract B apply(OperationOutput operationOutput);
@@ -352,7 +354,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* Returns the finally to be applied {@link BucketOperation} with the given alias.
*
* @param alias will never be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
public T as(String alias) {
@@ -548,7 +550,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
public Document toDocument(AggregationOperationContext context) {
List<Object> operationArguments = getOperationArguments(context);
return new Document(operation, operationArguments.size() == 1 ? operationArguments.get(0) : operationArguments);
return new Document(operation,
operationArguments.size() == 1 ? operationArguments.get(0) : operationArguments);
}
protected List<Object> getOperationArguments(AggregationOperationContext context) {
@@ -576,7 +579,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Returns the field that holds the {@link ProjectionOperationBuilder.OperationProjection}.
*
* @return never {@literal null}.
* @return
*/
protected Field getField() {
return getExposedField();
@@ -586,7 +589,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* Creates a new instance of this {@link OperationOutput} with the given alias.
*
* @param alias the alias to set
* @return new instance of {@link OperationOutput}.
* @return
*/
public OperationOutput withAlias(String alias) {
@@ -655,8 +658,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Creates a new {@link AggregationExpressionOutput}.
*
* @param field must not be {@literal null}.
* @param expression must not be {@literal null}.
* @param field
* @param expression
*/
protected AggregationExpressionOutput(Field field, AggregationExpression expression) {

View File

@@ -32,7 +32,7 @@ public class ComparisonOperators {
* Take the field referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ComparisonOperatorFactory}.
* @return
*/
public static ComparisonOperatorFactory valueOf(String fieldReference) {
return new ComparisonOperatorFactory(fieldReference);
@@ -42,7 +42,7 @@ public class ComparisonOperators {
* Take the value resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ComparisonOperatorFactory}.
* @return
*/
public static ComparisonOperatorFactory valueOf(AggregationExpression expression) {
return new ComparisonOperatorFactory(expression);
@@ -81,7 +81,7 @@ public class ComparisonOperators {
* Creates new {@link AggregationExpression} that compares two values.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareTo(String fieldReference) {
return createCmp().compareTo(fieldReference);
@@ -91,7 +91,7 @@ public class ComparisonOperators {
* Creates new {@link AggregationExpression} that compares two values.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareTo(AggregationExpression expression) {
return createCmp().compareTo(expression);
@@ -101,7 +101,7 @@ public class ComparisonOperators {
* Creates new {@link AggregationExpression} that compares two values.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareToValue(Object value) {
return createCmp().compareToValue(value);
@@ -116,7 +116,7 @@ public class ComparisonOperators {
* value is equal to the value of the referenced field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalTo(String fieldReference) {
return createEq().equalTo(fieldReference);
@@ -127,7 +127,7 @@ public class ComparisonOperators {
* value is equal to the expression result.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalTo(AggregationExpression expression) {
return createEq().equalTo(expression);
@@ -138,7 +138,7 @@ public class ComparisonOperators {
* value is equal to the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalToValue(Object value) {
return createEq().equalToValue(value);
@@ -153,7 +153,7 @@ public class ComparisonOperators {
* value is greater than the value of the referenced field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThan(String fieldReference) {
return createGt().greaterThan(fieldReference);
@@ -164,7 +164,7 @@ public class ComparisonOperators {
* value is greater than the expression result.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThan(AggregationExpression expression) {
return createGt().greaterThan(expression);
@@ -175,7 +175,7 @@ public class ComparisonOperators {
* value is greater than the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThanValue(Object value) {
return createGt().greaterThanValue(value);
@@ -190,7 +190,7 @@ public class ComparisonOperators {
* value is greater than or equivalent to the value of the referenced field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualTo(String fieldReference) {
return createGte().greaterThanEqualTo(fieldReference);
@@ -201,7 +201,7 @@ public class ComparisonOperators {
* value is greater than or equivalent to the expression result.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualTo(AggregationExpression expression) {
return createGte().greaterThanEqualTo(expression);
@@ -212,7 +212,7 @@ public class ComparisonOperators {
* value is greater than or equivalent to the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualToValue(Object value) {
return createGte().greaterThanEqualToValue(value);
@@ -227,7 +227,7 @@ public class ComparisonOperators {
* value is less than the value of the referenced field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThan(String fieldReference) {
return createLt().lessThan(fieldReference);
@@ -238,7 +238,7 @@ public class ComparisonOperators {
* value is less than the expression result.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThan(AggregationExpression expression) {
return createLt().lessThan(expression);
@@ -249,7 +249,7 @@ public class ComparisonOperators {
* value is less than to the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThanValue(Object value) {
return createLt().lessThanValue(value);
@@ -264,7 +264,7 @@ public class ComparisonOperators {
* value is less than or equivalent to the value of the referenced field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public Lte lessThanEqualTo(String fieldReference) {
return createLte().lessThanEqualTo(fieldReference);
@@ -275,7 +275,7 @@ public class ComparisonOperators {
* value is less than or equivalent to the expression result.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public Lte lessThanEqualTo(AggregationExpression expression) {
return createLte().lessThanEqualTo(expression);
@@ -285,8 +285,8 @@ public class ComparisonOperators {
* Creates new {@link AggregationExpression} that compares two values and returns {@literal true} when the first
* value is less than or equivalent to the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Lte}.
* @param value
* @return
*/
public Lte lessThanEqualToValue(Object value) {
return createLte().lessThanEqualToValue(value);
@@ -301,7 +301,7 @@ public class ComparisonOperators {
* are not equivalent.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualTo(String fieldReference) {
return createNe().notEqualTo(fieldReference);
@@ -312,7 +312,7 @@ public class ComparisonOperators {
* are not equivalent.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualTo(AggregationExpression expression) {
return createNe().notEqualTo(expression);
@@ -323,7 +323,7 @@ public class ComparisonOperators {
* are not equivalent.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualToValue(Object value) {
return createNe().notEqualToValue(value);
@@ -358,7 +358,7 @@ public class ComparisonOperators {
* Creates new {@link Cmp}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public static Cmp valueOf(String fieldReference) {
@@ -370,7 +370,7 @@ public class ComparisonOperators {
* Creates new {@link Cmp}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public static Cmp valueOf(AggregationExpression expression) {
@@ -382,7 +382,7 @@ public class ComparisonOperators {
* Creates new {@link Cmp} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareTo(String fieldReference) {
@@ -394,7 +394,7 @@ public class ComparisonOperators {
* Creates new {@link Cmp} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareTo(AggregationExpression expression) {
@@ -406,12 +406,12 @@ public class ComparisonOperators {
* Creates new {@link Cmp} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Cmp}.
* @return
*/
public Cmp compareToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Cmp(append(value, Expand.KEEP_SOURCE));
return new Cmp(append(value));
}
}
@@ -435,7 +435,7 @@ public class ComparisonOperators {
* Creates new {@link Eq}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public static Eq valueOf(String fieldReference) {
@@ -447,7 +447,7 @@ public class ComparisonOperators {
* Creates new {@link Eq}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public static Eq valueOf(AggregationExpression expression) {
@@ -459,7 +459,7 @@ public class ComparisonOperators {
* Creates new {@link Eq} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalTo(String fieldReference) {
@@ -471,7 +471,7 @@ public class ComparisonOperators {
* Creates new {@link Eq} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalTo(AggregationExpression expression) {
@@ -483,12 +483,12 @@ public class ComparisonOperators {
* Creates new {@link Eq} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Eq}.
* @return
*/
public Eq equalToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Eq(append(value, Expand.KEEP_SOURCE));
return new Eq(append(value));
}
}
@@ -512,7 +512,7 @@ public class ComparisonOperators {
* Creates new {@link Gt}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public static Gt valueOf(String fieldReference) {
@@ -524,7 +524,7 @@ public class ComparisonOperators {
* Creates new {@link Gt}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public static Gt valueOf(AggregationExpression expression) {
@@ -536,7 +536,7 @@ public class ComparisonOperators {
* Creates new {@link Gt} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThan(String fieldReference) {
@@ -548,7 +548,7 @@ public class ComparisonOperators {
* Creates new {@link Gt} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThan(AggregationExpression expression) {
@@ -560,7 +560,7 @@ public class ComparisonOperators {
* Creates new {@link Gt} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Gt}.
* @return
*/
public Gt greaterThanValue(Object value) {
@@ -589,7 +589,7 @@ public class ComparisonOperators {
* Creates new {@link Lt}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public static Lt valueOf(String fieldReference) {
@@ -601,7 +601,7 @@ public class ComparisonOperators {
* Creates new {@link Lt}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public static Lt valueOf(AggregationExpression expression) {
@@ -613,7 +613,7 @@ public class ComparisonOperators {
* Creates new {@link Lt} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThan(String fieldReference) {
@@ -625,7 +625,7 @@ public class ComparisonOperators {
* Creates new {@link Lt} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThan(AggregationExpression expression) {
@@ -637,7 +637,7 @@ public class ComparisonOperators {
* Creates new {@link Lt} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Lt}.
* @return
*/
public Lt lessThanValue(Object value) {
@@ -666,7 +666,7 @@ public class ComparisonOperators {
* Creates new {@link Gte}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public static Gte valueOf(String fieldReference) {
@@ -678,7 +678,7 @@ public class ComparisonOperators {
* Creates new {@link Gte}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public static Gte valueOf(AggregationExpression expression) {
@@ -690,7 +690,7 @@ public class ComparisonOperators {
* Creates new {@link Gte} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualTo(String fieldReference) {
@@ -702,7 +702,7 @@ public class ComparisonOperators {
* Creates new {@link Gte} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualTo(AggregationExpression expression) {
@@ -714,7 +714,7 @@ public class ComparisonOperators {
* Creates new {@link Gte} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Gte}.
* @return
*/
public Gte greaterThanEqualToValue(Object value) {
@@ -743,7 +743,7 @@ public class ComparisonOperators {
* Creates new {@link Lte}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public static Lte valueOf(String fieldReference) {
@@ -755,7 +755,7 @@ public class ComparisonOperators {
* Creates new {@link Lte}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public static Lte valueOf(AggregationExpression expression) {
@@ -767,7 +767,7 @@ public class ComparisonOperators {
* Creates new {@link Lte} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public Lte lessThanEqualTo(String fieldReference) {
@@ -779,7 +779,7 @@ public class ComparisonOperators {
* Creates new {@link Lte} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public Lte lessThanEqualTo(AggregationExpression expression) {
@@ -791,7 +791,7 @@ public class ComparisonOperators {
* Creates new {@link Lte} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Lte}.
* @return
*/
public Lte lessThanEqualToValue(Object value) {
@@ -820,7 +820,7 @@ public class ComparisonOperators {
* Creates new {@link Ne}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public static Ne valueOf(String fieldReference) {
@@ -832,7 +832,7 @@ public class ComparisonOperators {
* Creates new {@link Ne}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public static Ne valueOf(AggregationExpression expression) {
@@ -844,7 +844,7 @@ public class ComparisonOperators {
* Creates new {@link Ne} with all previously added arguments appending the given one.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualTo(String fieldReference) {
@@ -856,7 +856,7 @@ public class ComparisonOperators {
* Creates new {@link Ne} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualTo(AggregationExpression expression) {
@@ -868,12 +868,12 @@ public class ComparisonOperators {
* Creates new {@link Eq} with all previously added arguments appending the given one.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Ne}.
* @return
*/
public Ne notEqualToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Ne(append(value, Expand.KEEP_SOURCE));
return new Ne(append(value));
}
}
}

View File

@@ -43,7 +43,7 @@ public class ConditionalOperators {
* Take the field referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link ConditionalOperatorFactory}.
* @return
*/
public static ConditionalOperatorFactory when(String fieldReference) {
return new ConditionalOperatorFactory(fieldReference);
@@ -53,7 +53,7 @@ public class ConditionalOperators {
* Take the value resulting from the given {@literal expression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link ConditionalOperatorFactory}.
* @return
*/
public static ConditionalOperatorFactory when(AggregationExpression expression) {
return new ConditionalOperatorFactory(expression);
@@ -63,7 +63,7 @@ public class ConditionalOperators {
* Take the value resulting from the given {@literal criteriaDefinition}.
*
* @param criteriaDefinition must not be {@literal null}.
* @return new instance of {@link ConditionalOperatorFactory}.
* @return
*/
public static ConditionalOperatorFactory when(CriteriaDefinition criteriaDefinition) {
return new ConditionalOperatorFactory(criteriaDefinition);
@@ -75,7 +75,7 @@ public class ConditionalOperators {
* instances of undefined values or missing fields, returns the value of the replacement expression.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IfNull.ThenBuilder} to create {@link IfNull}.
* @return
*/
public static IfNull.ThenBuilder ifNull(String fieldReference) {
@@ -89,7 +89,7 @@ public class ConditionalOperators {
* instances of undefined values or missing fields, returns the value of the replacement expression.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IfNull.ThenBuilder} to create {@link IfNull}.
* @return
*/
public static IfNull.ThenBuilder ifNull(AggregationExpression expression) {
@@ -103,7 +103,7 @@ public class ConditionalOperators {
* out of the control flow.
*
* @param conditions must not be {@literal null}.
* @return new instance of {@link Switch}.
* @return
*/
public static Switch switchCases(CaseOperator... conditions) {
return Switch.switchCases(conditions);
@@ -115,7 +115,7 @@ public class ConditionalOperators {
* out of the control flow.
*
* @param conditions must not be {@literal null}.
* @return new instance of {@link Switch}.
* @return
*/
public static Switch switchCases(List<CaseOperator> conditions) {
return Switch.switchCases(conditions);
@@ -176,7 +176,7 @@ public class ConditionalOperators {
* return expressions.
*
* @param value must not be {@literal null}.
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
* @return
*/
public OtherwiseBuilder then(Object value) {
@@ -189,7 +189,7 @@ public class ConditionalOperators {
* return expressions.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
* @return
*/
public OtherwiseBuilder thenValueOf(AggregationExpression expression) {
@@ -202,7 +202,7 @@ public class ConditionalOperators {
* return expressions.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
* @return
*/
public OtherwiseBuilder thenValueOf(String fieldReference) {
@@ -233,9 +233,9 @@ public class ConditionalOperators {
* field references}, {@link AggregationExpression expressions}, values of simple MongoDB types or values that can be
* converted to a simple MongoDB type.
*
* @author Mark Paluch
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/">https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/</a>
* @author Mark Paluch
*/
public static class IfNull implements AggregationExpression {
@@ -251,9 +251,9 @@ public class ConditionalOperators {
/**
* Creates new {@link IfNull}.
*
* @param fieldReference the field to check for a {@literal null} value, field reference must not be
* {@literal null}.
* @return never {@literal null}.
* @param fieldReference the field to check for a {@literal null} value, field reference must not be {@literal null}
* .
* @return
*/
public static ThenBuilder ifNull(String fieldReference) {
@@ -266,7 +266,7 @@ public class ConditionalOperators {
*
* @param expression the expression to check for a {@literal null} value, field reference must not be
* {@literal null}.
* @return never {@literal null}.
* @return
*/
public static ThenBuilder ifNull(AggregationExpression expression) {
@@ -338,19 +338,19 @@ public class ConditionalOperators {
* @param value the value to be used if the {@code $ifNull} condition evaluates {@literal true}. Can be a
* {@link Document}, a value that is supported by MongoDB or a value that can be converted to a MongoDB
* representation but must not be {@literal null}.
* @return new instance of {@link IfNull}.
* @return
*/
IfNull then(Object value);
/**
* @param fieldReference the field holding the replacement value, must not be {@literal null}.
* @return new instance of {@link IfNull}.
* @return
*/
IfNull thenValueOf(String fieldReference);
/**
* @param expression the expression yielding to the replacement value, must not be {@literal null}.
* @return new instance of {@link IfNull}.
* @return
*/
IfNull thenValueOf(AggregationExpression expression);
}
@@ -461,12 +461,6 @@ public class ConditionalOperators {
return new Switch(Collections.<String, Object> singletonMap("branches", new ArrayList<CaseOperator>(conditions)));
}
/**
* Set the default value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Switch}.
*/
public Switch defaultTo(Object value) {
return new Switch(append("default", value));
}
@@ -528,7 +522,7 @@ public class ConditionalOperators {
* Set the then {@literal value}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link CaseOperator}.
* @return
*/
CaseOperator then(Object value);
}
@@ -542,10 +536,10 @@ public class ConditionalOperators {
* {@link AggregationExpression expressions}, values of simple MongoDB types or values that can be converted to a
* simple MongoDB type.
*
* @author Mark Paluch
* @author Christoph Strobl
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/cond/">https://docs.mongodb.com/manual/reference/operator/aggregation/cond/</a>
* @author Mark Paluch
* @author Christoph Strobl
*/
public static class Cond implements AggregationExpression {
@@ -670,6 +664,7 @@ public class ConditionalOperators {
}
clauses.add(new Document(key, args));
} else if (predicate instanceof Document) {
Document nested = (Document) predicate;
@@ -685,6 +680,7 @@ public class ConditionalOperators {
args.add(nested.get(s));
clauses.add(new Document(s, args));
}
} else if (!isKeyword(key)) {
List<Object> args = new ArrayList<Object>();

View File

@@ -34,9 +34,9 @@ public class CountOperation implements FieldsExposingAggregationOperation {
private final String fieldName;
/**
* Creates a new {@link CountOperation} given the {@literal fieldName} field name.
* Creates a new {@link CountOperation} given the {@link fieldName} field name.
*
* @param fieldName must not be {@literal null} or empty.
* @param asFieldName must not be {@literal null} or empty.
*/
public CountOperation(String fieldName) {
@@ -71,7 +71,7 @@ public class CountOperation implements FieldsExposingAggregationOperation {
* Returns the finally to be applied {@link CountOperation} with the given alias.
*
* @param fieldName must not be {@literal null} or empty.
* @return new instance of {@link CountOperation}.
* @return
*/
public CountOperation as(String fieldName) {
return new CountOperation(fieldName);

View File

@@ -30,7 +30,7 @@ public class DataTypeOperators {
* Return the BSON data type of the given {@literal field}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Type}.
* @return
*/
public static Type typeOf(String fieldReference) {
return Type.typeOf(fieldReference);
@@ -56,7 +56,7 @@ public class DataTypeOperators {
* Creates new {@link Type}.
*
* @param field must not be {@literal null}.
* @return new instance of {@link Type}.
* @return
*/
public static Type typeOf(String field) {

View File

@@ -37,7 +37,7 @@ public class DateOperators {
* Take the date referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link DateOperatorFactory}.
* @return
*/
public static DateOperatorFactory dateOf(String fieldReference) {
@@ -49,7 +49,7 @@ public class DateOperators {
* Take the date resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link DateOperatorFactory}.
* @return
*/
public static DateOperatorFactory dateOf(AggregationExpression expression) {
@@ -278,7 +278,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the day of the year for a date as a number between 1 and
* 366.
*
* @return new instance of {@link DayOfYear}.
* @return
*/
public DayOfYear dayOfYear() {
return applyTimezone(DayOfYear.dayOfYear(dateReference()), timezone);
@@ -288,7 +288,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the day of the month for a date as a number between 1 and
* 31.
*
* @return new instance of {@link DayOfMonth}.
* @return
*/
public DayOfMonth dayOfMonth() {
return applyTimezone(DayOfMonth.dayOfMonth(dateReference()), timezone);
@@ -298,7 +298,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the day of the week for a date as a number between 1
* (Sunday) and 7 (Saturday).
*
* @return new instance of {@link DayOfWeek}.
* @return
*/
public DayOfWeek dayOfWeek() {
return applyTimezone(DayOfWeek.dayOfWeek(dateReference()), timezone);
@@ -307,7 +307,7 @@ public class DateOperators {
/**
* Creates new {@link AggregationExpression} that returns the year portion of a date.
*
* @return new instance of {@link Year}.
* @return
*/
public Year year() {
return applyTimezone(Year.year(dateReference()), timezone);
@@ -316,7 +316,7 @@ public class DateOperators {
/**
* Creates new {@link AggregationExpression} that returns the month of a date as a number between 1 and 12.
*
* @return new instance of {@link Month}.
* @return
*/
public Month month() {
return applyTimezone(Month.month(dateReference()), timezone);
@@ -326,7 +326,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the week of the year for a date as a number between 0 and
* 53.
*
* @return new instance of {@link Week}.
* @return
*/
public Week week() {
return applyTimezone(Week.week(dateReference()), timezone);
@@ -335,7 +335,7 @@ public class DateOperators {
/**
* Creates new {@link AggregationExpression} that returns the hour portion of a date as a number between 0 and 23.
*
* @return new instance of {@link Hour}.
* @return
*/
public Hour hour() {
return applyTimezone(Hour.hour(dateReference()), timezone);
@@ -344,7 +344,7 @@ public class DateOperators {
/**
* Creates new {@link AggregationExpression} that returns the minute portion of a date as a number between 0 and 59.
*
* @return new instance of {@link Minute}.
* @return
*/
public Minute minute() {
return applyTimezone(Minute.minute(dateReference()), timezone);
@@ -354,7 +354,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the second portion of a date as a number between 0 and 59,
* but can be 60 to account for leap seconds.
*
* @return new instance of {@link Second}.
* @return
*/
public Second second() {
return applyTimezone(Second.second(dateReference()), timezone);
@@ -364,7 +364,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the millisecond portion of a date as an integer between 0
* and 999.
*
* @return new instance of {@link Millisecond}.
* @return
*/
public Millisecond millisecond() {
return applyTimezone(Millisecond.millisecond(dateReference()), timezone);
@@ -375,7 +375,7 @@ public class DateOperators {
* {@literal format}.
*
* @param format must not be {@literal null}.
* @return new instance of {@link DateToString}.
* @return
*/
public DateToString toString(String format) {
return applyTimezone(DateToString.dateToString(dateReference()).toString(format), timezone);
@@ -396,7 +396,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the weekday number in ISO 8601-2018 format, ranging from 1
* (for Monday) to 7 (for Sunday).
*
* @return new instance of {@link IsoDayOfWeek}.
* @return
*/
public IsoDayOfWeek isoDayOfWeek() {
return applyTimezone(IsoDayOfWeek.isoDayWeek(dateReference()), timezone);
@@ -406,7 +406,7 @@ public class DateOperators {
* Creates new {@link AggregationExpression} that returns the week number in ISO 8601-2018 format, ranging from 1 to
* 53.
*
* @return new instance of {@link IsoWeek}.
* @return
*/
public IsoWeek isoWeek() {
return applyTimezone(IsoWeek.isoWeek(dateReference()), timezone);
@@ -415,7 +415,7 @@ public class DateOperators {
/**
* Creates new {@link AggregationExpression} that returns the year number in ISO 8601-2018 format.
*
* @return new instance of {@link IsoWeekYear}.
* @return
*/
public IsoWeekYear isoWeekYear() {
return applyTimezone(IsoWeekYear.isoWeekYear(dateReference()), timezone);
@@ -642,7 +642,7 @@ public class DateOperators {
* Creates new {@link DayOfYear}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link DayOfYear}.
* @return
*/
public static DayOfYear dayOfYear(String fieldReference) {
@@ -654,7 +654,7 @@ public class DateOperators {
* Creates new {@link DayOfYear}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link DayOfYear}.
* @return
*/
public static DayOfYear dayOfYear(AggregationExpression expression) {
@@ -714,7 +714,7 @@ public class DateOperators {
* Creates new {@link DayOfMonth}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link DayOfMonth}.
* @return
*/
public static DayOfMonth dayOfMonth(String fieldReference) {
@@ -726,7 +726,7 @@ public class DateOperators {
* Creates new {@link DayOfMonth}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link DayOfMonth}.
* @return
*/
public static DayOfMonth dayOfMonth(AggregationExpression expression) {
@@ -786,7 +786,7 @@ public class DateOperators {
* Creates new {@link DayOfWeek}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link DayOfWeek}.
* @return
*/
public static DayOfWeek dayOfWeek(String fieldReference) {
@@ -798,7 +798,7 @@ public class DateOperators {
* Creates new {@link DayOfWeek}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link DayOfWeek}.
* @return
*/
public static DayOfWeek dayOfWeek(AggregationExpression expression) {
@@ -858,7 +858,7 @@ public class DateOperators {
* Creates new {@link Year}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Year}.
* @return
*/
public static Year yearOf(String fieldReference) {
@@ -870,7 +870,7 @@ public class DateOperators {
* Creates new {@link Year}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Year}.
* @return
*/
public static Year yearOf(AggregationExpression expression) {
@@ -930,7 +930,7 @@ public class DateOperators {
* Creates new {@link Month}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Month}.
* @return
*/
public static Month monthOf(String fieldReference) {
@@ -942,7 +942,7 @@ public class DateOperators {
* Creates new {@link Month}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Month}.
* @return
*/
public static Month monthOf(AggregationExpression expression) {
@@ -1002,7 +1002,7 @@ public class DateOperators {
* Creates new {@link Week}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Week}.
* @return
*/
public static Week weekOf(String fieldReference) {
@@ -1014,7 +1014,7 @@ public class DateOperators {
* Creates new {@link Week}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Week}.
* @return
*/
public static Week weekOf(AggregationExpression expression) {
@@ -1074,7 +1074,7 @@ public class DateOperators {
* Creates new {@link Hour}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Hour}.
* @return
*/
public static Hour hourOf(String fieldReference) {
@@ -1086,7 +1086,7 @@ public class DateOperators {
* Creates new {@link Hour}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Hour}.
* @return
*/
public static Hour hourOf(AggregationExpression expression) {
@@ -1146,7 +1146,7 @@ public class DateOperators {
* Creates new {@link Minute}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Minute}.
* @return
*/
public static Minute minuteOf(String fieldReference) {
@@ -1158,7 +1158,7 @@ public class DateOperators {
* Creates new {@link Minute}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Minute}.
* @return
*/
public static Minute minuteOf(AggregationExpression expression) {
@@ -1218,7 +1218,7 @@ public class DateOperators {
* Creates new {@link Second}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Second}.
* @return
*/
public static Second secondOf(String fieldReference) {
@@ -1230,7 +1230,7 @@ public class DateOperators {
* Creates new {@link Second}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Second}.
* @return
*/
public static Second secondOf(AggregationExpression expression) {
@@ -1290,7 +1290,7 @@ public class DateOperators {
* Creates new {@link Millisecond}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Millisecond}.
* @return
*/
public static Millisecond millisecondOf(String fieldReference) {
@@ -1302,7 +1302,7 @@ public class DateOperators {
* Creates new {@link Millisecond}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Millisecond}.
* @return
*/
public static Millisecond millisecondOf(AggregationExpression expression) {
@@ -1376,7 +1376,7 @@ public class DateOperators {
* Creates new {@link FormatBuilder} allowing to define the date format to apply.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link FormatBuilder} to crate {@link DateToString}.
* @return
*/
public static FormatBuilder dateOf(final String fieldReference) {
@@ -1388,7 +1388,7 @@ public class DateOperators {
* Creates new {@link FormatBuilder} allowing to define the date format to apply.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link FormatBuilder} to crate {@link DateToString}.
* @return
*/
public static FormatBuilder dateOf(final AggregationExpression expression) {
@@ -1540,7 +1540,7 @@ public class DateOperators {
* Creates new {@link IsoDayOfWeek}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IsoDayOfWeek}.
* @return
*/
public static IsoDayOfWeek isoDayOfWeek(String fieldReference) {
@@ -1552,7 +1552,7 @@ public class DateOperators {
* Creates new {@link IsoDayOfWeek}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IsoDayOfWeek}.
* @return
*/
public static IsoDayOfWeek isoDayOfWeek(AggregationExpression expression) {
@@ -1612,7 +1612,7 @@ public class DateOperators {
* Creates new {@link IsoWeek}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IsoWeek}.
* @return
*/
public static IsoWeek isoWeekOf(String fieldReference) {
@@ -1624,7 +1624,7 @@ public class DateOperators {
* Creates new {@link IsoWeek}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IsoWeek}.
* @return
*/
public static IsoWeek isoWeekOf(AggregationExpression expression) {
@@ -1684,7 +1684,7 @@ public class DateOperators {
* Creates new {@link IsoWeekYear}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IsoWeekYear}.
* @return
*/
public static IsoWeekYear isoWeekYearOf(String fieldReference) {
@@ -1696,7 +1696,7 @@ public class DateOperators {
* Creates new {@link Millisecond}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IsoWeekYear}.
* @return
*/
public static IsoWeekYear isoWeekYearOf(AggregationExpression expression) {
@@ -2378,7 +2378,6 @@ public class DateOperators {
@SuppressWarnings("unchecked")
private static <T extends TimezonedDateAggregationExpression> T applyTimezone(T instance, Timezone timezone) {
return !ObjectUtils.nullSafeEquals(Timezone.none(), timezone) && !instance.hasTimezone()
? (T) instance.withTimezone(timezone)
: instance;
? (T) instance.withTimezone(timezone) : instance;
}
}

View File

@@ -46,7 +46,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
/**
* Returns an empty {@link ExposedFields} instance.
*
* @return never {@literal null}.
* @return
* @since 2.0
*/
public static ExposedFields empty() {
@@ -57,7 +57,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
* Creates a new {@link ExposedFields} instance from the given {@link ExposedField}s.
*
* @param fields must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public static ExposedFields from(ExposedField... fields) {
return from(Arrays.asList(fields));
@@ -67,7 +67,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
* Creates a new {@link ExposedFields} instance from the given {@link ExposedField}s.
*
* @param fields must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
private static ExposedFields from(List<ExposedField> fields) {
@@ -84,7 +84,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
* Creates synthetic {@link ExposedFields} from the given {@link Fields}.
*
* @param fields must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public static ExposedFields synthetic(Fields fields) {
return createFields(fields, true);
@@ -94,7 +94,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
* Creates non-synthetic {@link ExposedFields} from the given {@link Fields}.
*
* @param fields must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
public static ExposedFields nonSynthetic(Fields fields) {
return createFields(fields, false);
@@ -105,7 +105,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
*
* @param fields must not be {@literal null}.
* @param synthetic
* @return never {@literal null}.
* @return
*/
private static ExposedFields createFields(Fields fields, boolean synthetic) {
@@ -135,7 +135,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
* Creates a new {@link ExposedFields} adding the given {@link ExposedField}.
*
* @param field must not be {@literal null}.
* @return new instance of {@link ExposedFields}.
* @return
*/
public ExposedFields and(ExposedField field) {
@@ -151,8 +151,8 @@ public final class ExposedFields implements Iterable<ExposedField> {
/**
* Returns the field with the given name or {@literal null} if no field with the given name is available.
*
* @param name must not be {@literal null}.
* @return can be {@literal null}.
* @param name
* @return
*/
@Nullable
public ExposedField getField(String name) {

View File

@@ -146,7 +146,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Set the {@literal collectionName} to apply the {@code $graphLookup} to.
*
* @param collectionName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
StartWithBuilder from(String collectionName);
}
@@ -161,7 +161,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Set the startWith {@literal fieldReferences} to apply the {@code $graphLookup} to.
*
* @param fieldReferences must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
ConnectFromBuilder startWith(String... fieldReferences);
@@ -169,7 +169,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Set the startWith {@literal expressions} to apply the {@code $graphLookup} to.
*
* @param expressions must not be {@literal null}.
* @return never {@literal null}.
* @return
*/
ConnectFromBuilder startWith(AggregationExpression... expressions);
@@ -178,7 +178,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* {@link AggregationExpression} to apply the {@code $graphLookup} to.
*
* @param expressions must not be {@literal null}.
* @return never {@literal null}.
* @return
* @throws IllegalArgumentException
*/
ConnectFromBuilder startWith(Object... expressions);
@@ -193,7 +193,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Set the connectFrom {@literal fieldName} to apply the {@code $graphLookup} to.
*
* @param fieldName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
ConnectToBuilder connectFrom(String fieldName);
}
@@ -207,7 +207,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Set the connectTo {@literal fieldName} to apply the {@code $graphLookup} to.
*
* @param fieldName must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
GraphLookupOperationBuilder connectTo(String fieldName);
}
@@ -360,7 +360,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Optionally limit the number of recursions.
*
* @param numberOfRecursions must be greater or equal to zero.
* @return this.
* @return
*/
public GraphLookupOperationBuilder maxDepth(long numberOfRecursions) {
@@ -374,7 +374,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Optionally add a depth field {@literal fieldName} to each traversed document in the search path.
*
* @param fieldName must not be {@literal null} or empty.
* @return this.
* @return
*/
public GraphLookupOperationBuilder depthField(String fieldName) {

View File

@@ -89,7 +89,7 @@ public class LookupOperation implements FieldsExposingAggregationOperation, Inhe
/**
* Get a builder that allows creation of {@link LookupOperation}.
*
* @return never {@literal null}.
* @return
*/
public static FromBuilder newLookup() {
return new LookupOperationBuilder();
@@ -99,7 +99,7 @@ public class LookupOperation implements FieldsExposingAggregationOperation, Inhe
/**
* @param name the collection in the same database to perform the join with, must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
LocalFieldBuilder from(String name);
}
@@ -109,7 +109,7 @@ public class LookupOperation implements FieldsExposingAggregationOperation, Inhe
/**
* @param name the field from the documents input to the {@code $lookup} stage, must not be {@literal null} or
* empty.
* @return never {@literal null}.
* @return
*/
ForeignFieldBuilder localField(String name);
}
@@ -118,7 +118,7 @@ public class LookupOperation implements FieldsExposingAggregationOperation, Inhe
/**
* @param name the field from the documents in the {@code from} collection, must not be {@literal null} or empty.
* @return never {@literal null}.
* @return
*/
AsBuilder foreignField(String name);
}
@@ -127,7 +127,7 @@ public class LookupOperation implements FieldsExposingAggregationOperation, Inhe
/**
* @param name the name of the new array field to add to the input documents, must not be {@literal null} or empty.
* @return new instance of {@link LookupOperation}.
* @return
*/
LookupOperation as(String name);
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2019-2020 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.springframework.data.mapping.context.InvalidPersistentPropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.DirectFieldReference;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
/**
* A {@link TypeBasedAggregationOperationContext} with less restrictive field reference handling, suppressing
* {@link InvalidPersistentPropertyPath} exceptions when resolving mapped field names.
*
* @author Christoph Strobl
* @since 3.0
*/
public class RelaxedTypeBasedAggregationOperationContext extends TypeBasedAggregationOperationContext {
/**
* Creates a new {@link TypeBasedAggregationOperationContext} for the given type, {@link MappingContext} and
* {@link QueryMapper}.
*
* @param type must not be {@literal null}.
* @param mappingContext must not be {@literal null}.
* @param mapper must not be {@literal null}.
*/
public RelaxedTypeBasedAggregationOperationContext(Class<?> type,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext, QueryMapper mapper) {
super(type, mappingContext, mapper);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext#getReferenceFor(rg.springframework.data.mongodb.core.aggregation.Field)
*/
@Override
protected FieldReference getReferenceFor(Field field) {
try {
return super.getReferenceFor(field);
} catch (InvalidPersistentPropertyPath e) {
return new DirectFieldReference(new ExposedField(field, true));
}
}
}

View File

@@ -33,7 +33,8 @@ import org.springframework.util.Assert;
* @author Mark Paluch
* @author Christoph Strobl
* @since 1.10
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/">MongoDB Aggregation Framework: $replaceRoot</a>
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/">MongoDB Aggregation
* Framework: $replaceRoot</a>
*/
public class ReplaceRootOperation implements FieldsExposingAggregationOperation {
@@ -82,7 +83,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
*/
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$replaceRoot", new Document("newRoot", replacement.toDocumentExpression(context)));
return new Document("$replaceRoot", new Document("newRoot", getReplacement().toDocumentExpression(context)));
}
/* (non-Javadoc)
@@ -93,6 +94,16 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
return ExposedFields.from();
}
/**
* Obtain the {@link Replacement}.
*
* @return never {@literal null}.
* @since 3.0
*/
protected Replacement getReplacement() {
return replacement;
}
/**
* Builder for {@link ReplaceRootOperation}.
*
@@ -335,7 +346,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
/**
* Creates a {@link ReplacementDocument} given {@link ReplacementContributor}.
*
* @param contributor must not be {@literal null}.
* @param contributor
*/
protected ReplacementDocument(ReplacementContributor contributor) {
@@ -351,7 +362,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
* Creates a {@link ReplacementDocument} given a {@literal value}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link ReplacementDocument}.
* @return
*/
public static ReplacementDocument valueOf(Object value) {
return new ReplacementDocument(new DocumentContributor(value));
@@ -361,7 +372,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
* Creates a {@link ReplacementDocument} given a single {@literal field} and {@link AggregationExpression}.
*
* @param aggregationExpression must not be {@literal null}.
* @return new instance of {@link ReplacementDocument}.
* @return
*/
public static ReplacementDocument forExpression(String field, AggregationExpression aggregationExpression) {
return new ReplacementDocument(new ExpressionFieldContributor(Fields.field(field), aggregationExpression));
@@ -371,7 +382,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
* Creates a {@link ReplacementDocument} given a single {@literal field} and {@literal value}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link ReplacementDocument}.
* @return
*/
public static ReplacementDocument forSingleValue(String field, Object value) {
return new ReplacementDocument(new ValueFieldContributor(Fields.field(field), value));
@@ -427,7 +438,7 @@ public class ReplaceRootOperation implements FieldsExposingAggregationOperation
* {@link AggregationOperationContext}.
*
* @param context will never be {@literal null}.
* @return never {@literal null}.
* @return
*/
Document toDocument(AggregationOperationContext context);
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2019-2020 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 java.util.Collection;
import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.util.Assert;
/**
* Encapsulates the aggregation framework {@code $replaceRoot}-operation. <br />
* The operation replaces all existing fields including the {@code id} field with @{code $replaceWith}. This way it is
* possible to promote an embedded document to the top-level or specify a new document.
*
* @author Christoph Strobl
* @since 3.0
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/replaceWith/">MongoDB Aggregation
* Framework: $replaceWith</a>
*/
public class ReplaceWithOperation extends ReplaceRootOperation {
/**
* Creates new instance of {@link ReplaceWithOperation}.
*
* @param replacement must not be {@literal null}.
*/
public ReplaceWithOperation(Replacement replacement) {
super(replacement);
}
/**
* Creates new instance of {@link ReplaceWithOperation}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link ReplaceWithOperation}.
*/
public static ReplaceWithOperation replaceWithValue(Object value) {
return new ReplaceWithOperation((ctx) -> value);
}
/**
* Creates new instance of {@link ReplaceWithOperation} treating a given {@link String} {@literal value} as a
* {@link Field field reference}.
*
* @param value must not be {@literal null}.
* @return
*/
public static ReplaceWithOperation replaceWithValueOf(Object value) {
Assert.notNull(value, "Value must not be null!");
return new ReplaceWithOperation((ctx) -> {
Object target = value instanceof String ? Fields.field((String) value) : value;
return computeValue(target, ctx);
});
}
private static Object computeValue(Object value, AggregationOperationContext context) {
if (value instanceof Field) {
return context.getReference((Field) value).toString();
}
if (value instanceof AggregationExpression) {
return ((AggregationExpression) value).toDocument(context);
}
if (value instanceof Collection) {
return ((Collection) value).stream().map(it -> computeValue(it, context)).collect(Collectors.toList());
}
return value;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {
return context.getMappedObject(new Document("$replaceWith", getReplacement().toDocumentExpression(context)));
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright 2019-2020 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 java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
import org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation.InheritsFieldsAggregationOperation;
import org.springframework.data.mongodb.core.aggregation.SetOperation.FieldAppender.ValueAppender;
import org.springframework.lang.Nullable;
/**
* Adds new fields to documents. {@code $set} outputs documents that contain all existing fields from the input
* documents and newly added fields.
*
* <pre class="code">
* SetOperation.set("totalHomework").toValue("A+").and().set("totalQuiz").toValue("B-")
* </pre>
*
* @author Christoph Strobl
* @since 3.0
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/set/">MongoDB Aggregation Framework:
* $set</a>
*/
public class SetOperation implements InheritsFieldsAggregationOperation {
private Map<Object, Object> valueMap;
private ExposedFields exposedFields = ExposedFields.empty();
/**
* Create new instance of {@link SetOperation} adding map keys as exposed fields.
*
* @param source must not be {@literal null}.
*/
private SetOperation(Map<Object, Object> source) {
this.valueMap = new LinkedHashMap<>(source);
for (Object key : source.keySet()) {
this.exposedFields = add(key);
}
}
/**
* Create new instance of {@link SetOperation}
*
* @param field must not be {@literal null}.
* @param value can be {@literal null}.
*/
public SetOperation(Object field, @Nullable Object value) {
this(Collections.singletonMap(field, value));
}
/**
* Define the {@link SetOperation} via {@link FieldAppender}.
*
* @return new instance of {@link FieldAppender}.
*/
public static FieldAppender builder() {
return new FieldAppender();
}
/**
* Concatenate another field to set.
*
* @param field must not be {@literal null}.
* @return new instance of {@link ValueAppender}.
*/
public static ValueAppender set(String field) {
return new FieldAppender().set(field);
}
/**
* Append the value for a specific field to the operation.
*
* @param field the target field to set.
* @param value the value to assign.
* @return new instance of {@link SetOperation}.
*/
public SetOperation set(Object field, Object value) {
LinkedHashMap<Object, Object> target = new LinkedHashMap<>(this.valueMap);
target.put(field, value);
return new SetOperation(target);
}
/**
* Concatenate additional fields to set.
*
* @return new instance of {@link FieldAppender}.
*/
public FieldAppender and() {
return new FieldAppender(this.valueMap);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {
InheritingExposedFieldsAggregationOperationContext operationContext = new InheritingExposedFieldsAggregationOperationContext(
exposedFields, context);
if (valueMap.size() == 1) {
return context
.getMappedObject(new Document("$set", toSetEntry(valueMap.entrySet().iterator().next(), operationContext)));
}
Document $set = new Document();
valueMap.entrySet().stream().map(it -> toSetEntry(it, operationContext)).forEach($set::putAll);
return context.getMappedObject(new Document("$set", $set));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation#getFields()
*/
@Override
public ExposedFields getFields() {
return exposedFields;
}
private ExposedFields add(Object field) {
if (field instanceof Field) {
return exposedFields.and(new ExposedField((Field) field, true));
}
if (field instanceof String) {
return exposedFields.and(new ExposedField(Fields.field((String) field), true));
}
throw new IllegalArgumentException(String.format("Expected %s to be a field/property.", field));
}
private static Document toSetEntry(Entry<Object, Object> entry, AggregationOperationContext context) {
String field = entry.getKey() instanceof String ? context.getReference((String) entry.getKey()).getRaw()
: context.getReference((Field) entry.getKey()).getRaw();
Object value = computeValue(entry.getValue(), context);
return new Document(field, value);
}
private static Object computeValue(Object value, AggregationOperationContext context) {
if (value instanceof Field) {
return context.getReference((Field) value).toString();
}
if (value instanceof AggregationExpression) {
return ((AggregationExpression) value).toDocument(context);
}
if (value instanceof Collection) {
return ((Collection) value).stream().map(it -> computeValue(it, context)).collect(Collectors.toList());
}
return value;
}
/**
* @author Christoph Strobl
* @since 3.0
*/
public static class FieldAppender {
private final Map<Object, Object> valueMap;
private FieldAppender() {
this.valueMap = new LinkedHashMap<>();
}
private FieldAppender(Map<Object, Object> source) {
this.valueMap = new LinkedHashMap<>(source);
}
/**
* Define the field to set.
*
* @param field must not be {@literal null}.
* @return new instance of {@link ValueAppender}.
*/
public ValueAppender set(String field) {
return new ValueAppender() {
@Override
public SetOperation toValue(Object value) {
valueMap.put(field, value);
return FieldAppender.this.build();
}
@Override
public SetOperation toValueOf(Object value) {
valueMap.put(field, value instanceof String ? Fields.fields((String) value) : value);
return FieldAppender.this.build();
}
};
}
private SetOperation build() {
return new SetOperation(valueMap);
}
/**
* @author Christoph Strobl
* @since 3.0
*/
public interface ValueAppender {
/**
* Define the value to assign as is.
*
* @param value can be {@literal null}.
* @return new instance of {@link SetOperation}.
*/
SetOperation toValue(@Nullable Object value);
/**
* Define the value to assign. Plain {@link String} values are treated as {@link Field field references}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link SetOperation}.
*/
SetOperation toValueOf(Object value);
}
}
}

View File

@@ -34,7 +34,7 @@ public class SetOperators {
* Take the array referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link SetOperatorFactory}.
* @return
*/
public static SetOperatorFactory arrayAsSet(String fieldReference) {
return new SetOperatorFactory(fieldReference);
@@ -44,7 +44,7 @@ public class SetOperators {
* Take the array resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetOperatorFactory}.
* @return
*/
public static SetOperatorFactory arrayAsSet(AggregationExpression expression) {
return new SetOperatorFactory(expression);
@@ -87,7 +87,7 @@ public class SetOperators {
* returns {@literal true} if they have the same distinct elements and {@literal false} otherwise.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public SetEquals isEqualTo(String... arrayReferences) {
return createSetEquals().isEqualTo(arrayReferences);
@@ -98,7 +98,7 @@ public class SetOperators {
* returns {@literal true} if they have the same distinct elements and {@literal false} otherwise.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public SetEquals isEqualTo(AggregationExpression... expressions) {
return createSetEquals().isEqualTo(expressions);
@@ -113,7 +113,7 @@ public class SetOperators {
* arrays and returns an array that contains the elements that appear in every of those.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public SetIntersection intersects(String... arrayReferences) {
return createSetIntersection().intersects(arrayReferences);
@@ -124,7 +124,7 @@ public class SetOperators {
* arrays and returns an array that contains the elements that appear in every of those.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public SetIntersection intersects(AggregationExpression... expressions) {
return createSetIntersection().intersects(expressions);
@@ -139,7 +139,7 @@ public class SetOperators {
* arrays and returns an array that contains the elements that appear in any of those.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public SetUnion union(String... arrayReferences) {
return createSetUnion().union(arrayReferences);
@@ -150,7 +150,7 @@ public class SetOperators {
* arrays and returns an array that contains the elements that appear in any of those.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public SetUnion union(AggregationExpression... expressions) {
return createSetUnion().union(expressions);
@@ -165,7 +165,7 @@ public class SetOperators {
* containing the elements that do not exist in the given {@literal arrayReference}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public SetDifference differenceTo(String arrayReference) {
return createSetDifference().differenceTo(arrayReference);
@@ -176,7 +176,7 @@ public class SetOperators {
* containing the elements that do not exist in the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public SetDifference differenceTo(AggregationExpression expression) {
return createSetDifference().differenceTo(expression);
@@ -191,7 +191,7 @@ public class SetOperators {
* {@literal true} if it is a subset of the given {@literal arrayReference}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public SetIsSubset isSubsetOf(String arrayReference) {
return createSetIsSubset().isSubsetOf(arrayReference);
@@ -202,7 +202,7 @@ public class SetOperators {
* {@literal true} if it is a subset of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public SetIsSubset isSubsetOf(AggregationExpression expression) {
return createSetIsSubset().isSubsetOf(expression);
@@ -216,7 +216,7 @@ public class SetOperators {
* Creates new {@link AggregationExpression} that takes array of the previously mentioned field and returns
* {@literal true} if any of the elements are {@literal true} and {@literal false} otherwise.
*
* @return new instance of {@link AnyElementTrue}.
* @return
*/
public AnyElementTrue anyElementTrue() {
return usesFieldRef() ? AnyElementTrue.arrayAsSet(fieldReference) : AnyElementTrue.arrayAsSet(expression);
@@ -226,7 +226,7 @@ public class SetOperators {
* Creates new {@link AggregationExpression} that tkes array of the previously mentioned field and returns
* {@literal true} if no elements is {@literal false}.
*
* @return new instance of {@link AllElementsTrue}.
* @return
*/
public AllElementsTrue allElementsTrue() {
return usesFieldRef() ? AllElementsTrue.arrayAsSet(fieldReference) : AllElementsTrue.arrayAsSet(expression);
@@ -257,7 +257,7 @@ public class SetOperators {
* Create new {@link SetEquals}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public static SetEquals arrayAsSet(String arrayReference) {
@@ -269,7 +269,7 @@ public class SetOperators {
* Create new {@link SetEquals}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public static SetEquals arrayAsSet(AggregationExpression expression) {
@@ -281,7 +281,7 @@ public class SetOperators {
* Creates new {@link java.util.Set} with all previously added arguments appending the given one.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public SetEquals isEqualTo(String... arrayReferences) {
@@ -293,7 +293,7 @@ public class SetOperators {
* Creates new {@link Sum} with all previously added arguments appending the given one.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public SetEquals isEqualTo(AggregationExpression... expressions) {
@@ -305,7 +305,7 @@ public class SetOperators {
* Creates new {@link Sum} with all previously added arguments appending the given one.
*
* @param array must not be {@literal null}.
* @return new instance of {@link SetEquals}.
* @return
*/
public SetEquals isEqualTo(Object[] array) {
@@ -334,7 +334,7 @@ public class SetOperators {
* Creates new {@link SetIntersection}
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public static SetIntersection arrayAsSet(String arrayReference) {
@@ -346,7 +346,7 @@ public class SetOperators {
* Creates new {@link SetIntersection}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public static SetIntersection arrayAsSet(AggregationExpression expression) {
@@ -358,7 +358,7 @@ public class SetOperators {
* Creates new {@link SetIntersection} with all previously added arguments appending the given one.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public SetIntersection intersects(String... arrayReferences) {
@@ -370,7 +370,7 @@ public class SetOperators {
* Creates new {@link SetIntersection} with all previously added arguments appending the given one.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetIntersection}.
* @return
*/
public SetIntersection intersects(AggregationExpression... expressions) {
@@ -399,7 +399,7 @@ public class SetOperators {
* Creates new {@link SetUnion}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public static SetUnion arrayAsSet(String arrayReference) {
@@ -411,7 +411,7 @@ public class SetOperators {
* Creates new {@link SetUnion}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public static SetUnion arrayAsSet(AggregationExpression expression) {
@@ -423,7 +423,7 @@ public class SetOperators {
* Creates new {@link SetUnion} with all previously added arguments appending the given one.
*
* @param arrayReferences must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public SetUnion union(String... arrayReferences) {
@@ -435,7 +435,7 @@ public class SetOperators {
* Creates new {@link SetUnion} with all previously added arguments appending the given one.
*
* @param expressions must not be {@literal null}.
* @return new instance of {@link SetUnion}.
* @return
*/
public SetUnion union(AggregationExpression... expressions) {
@@ -464,7 +464,7 @@ public class SetOperators {
* Creates new {@link SetDifference}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public static SetDifference arrayAsSet(String arrayReference) {
@@ -476,7 +476,7 @@ public class SetOperators {
* Creates new {@link SetDifference}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public static SetDifference arrayAsSet(AggregationExpression expression) {
@@ -488,7 +488,7 @@ public class SetOperators {
* Creates new {@link SetDifference} with all previously added arguments appending the given one.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public SetDifference differenceTo(String arrayReference) {
@@ -500,7 +500,7 @@ public class SetOperators {
* Creates new {@link SetDifference} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetDifference}.
* @return
*/
public SetDifference differenceTo(AggregationExpression expression) {
@@ -529,7 +529,7 @@ public class SetOperators {
* Creates new {@link SetIsSubset}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public static SetIsSubset arrayAsSet(String arrayReference) {
@@ -541,7 +541,7 @@ public class SetOperators {
* Creates new {@link SetIsSubset}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public static SetIsSubset arrayAsSet(AggregationExpression expression) {
@@ -553,7 +553,7 @@ public class SetOperators {
* Creates new {@link SetIsSubset} with all previously added arguments appending the given one.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public SetIsSubset isSubsetOf(String arrayReference) {
@@ -565,7 +565,7 @@ public class SetOperators {
* Creates new {@link SetIsSubset} with all previously added arguments appending the given one.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SetIsSubset}.
* @return
*/
public SetIsSubset isSubsetOf(AggregationExpression expression) {
@@ -594,7 +594,7 @@ public class SetOperators {
* Creates new {@link AnyElementTrue}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link AnyElementTrue}.
* @return
*/
public static AnyElementTrue arrayAsSet(String arrayReference) {
@@ -606,7 +606,7 @@ public class SetOperators {
* Creates new {@link AnyElementTrue}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link AnyElementTrue}.
* @return
*/
public static AnyElementTrue arrayAsSet(AggregationExpression expression) {
@@ -639,7 +639,7 @@ public class SetOperators {
* Creates new {@link AllElementsTrue}.
*
* @param arrayReference must not be {@literal null}.
* @return new instance of {@link AllElementsTrue}.
* @return
*/
public static AllElementsTrue arrayAsSet(String arrayReference) {
@@ -651,7 +651,7 @@ public class SetOperators {
* Creates new {@link AllElementsTrue}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link AllElementsTrue}.
* @return
*/
public static AllElementsTrue arrayAsSet(AggregationExpression expression) {

View File

@@ -35,7 +35,7 @@ public class StringOperators {
* Take the array referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StringOperatorFactory}.
* @return
*/
public static StringOperatorFactory valueOf(String fieldReference) {
return new StringOperatorFactory(fieldReference);
@@ -45,7 +45,7 @@ public class StringOperators {
* Take the array referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StringOperatorFactory}.
* @return
*/
public static StringOperatorFactory valueOf(AggregationExpression fieldReference) {
return new StringOperatorFactory(fieldReference);
@@ -88,7 +88,7 @@ public class StringOperators {
* of the referenced field to it.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public Concat concatValueOf(String fieldReference) {
@@ -101,7 +101,7 @@ public class StringOperators {
* of the given {@link AggregationExpression} to it.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public Concat concatValueOf(AggregationExpression expression) {
@@ -114,7 +114,7 @@ public class StringOperators {
* {@literal value} to it.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public Concat concat(String value) {
@@ -130,8 +130,8 @@ public class StringOperators {
* Creates new {@link AggregationExpression} that takes the associated string representation and returns a substring
* starting at a specified index position.
*
* @param start start index number (including)
* @return new instance of {@link Substr}.
* @param start
* @return
*/
public Substr substring(int start) {
return substring(start, -1);
@@ -141,9 +141,9 @@ public class StringOperators {
* Creates new {@link AggregationExpression} that takes the associated string representation and returns a substring
* starting at a specified index position including the specified number of characters.
*
* @param start start index number (including)
* @param nrOfChars number of characters.
* @return new instance of {@link Substr}.
* @param start
* @param nrOfChars
* @return
*/
public Substr substring(int start, int nrOfChars) {
return createSubstr().substring(start, nrOfChars);
@@ -156,7 +156,7 @@ public class StringOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated string representation and lowers it.
*
* @return new instance of {@link ToLower}.
* @return
*/
public ToLower toLower() {
return usesFieldRef() ? ToLower.lowerValueOf(fieldReference) : ToLower.lowerValueOf(expression);
@@ -165,7 +165,7 @@ public class StringOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated string representation and uppers it.
*
* @return new instance of {@link ToUpper}.
* @return
*/
public ToUpper toUpper() {
return usesFieldRef() ? ToUpper.upperValueOf(fieldReference) : ToUpper.upperValueOf(expression);
@@ -176,7 +176,7 @@ public class StringOperators {
* case-insensitive comparison to the given {@literal value}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link StrCaseCmp}.
* @return
*/
public StrCaseCmp strCaseCmp(String value) {
@@ -189,7 +189,7 @@ public class StringOperators {
* case-insensitive comparison to the referenced {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StrCaseCmp}.
* @return
*/
public StrCaseCmp strCaseCmpValueOf(String fieldReference) {
@@ -202,7 +202,7 @@ public class StringOperators {
* case-insensitive comparison to the result of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StrCaseCmp}.
* @return
*/
public StrCaseCmp strCaseCmpValueOf(AggregationExpression expression) {
@@ -220,7 +220,7 @@ public class StringOperators {
* occurrence.
*
* @param substring must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(String substring) {
@@ -234,7 +234,7 @@ public class StringOperators {
* index (zero-based) of the first occurrence.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(Field fieldReference) {
@@ -248,7 +248,7 @@ public class StringOperators {
* byte index (zero-based) of the first occurrence.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(AggregationExpression expression) {
@@ -266,7 +266,7 @@ public class StringOperators {
* first occurrence.
*
* @param substring must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP indexOfCP(String substring) {
@@ -280,7 +280,7 @@ public class StringOperators {
* point index (zero-based) of the first occurrence.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP indexOfCP(Field fieldReference) {
@@ -294,7 +294,7 @@ public class StringOperators {
* code point index (zero-based) of the first occurrence.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP indexOfCP(AggregationExpression expression) {
@@ -311,7 +311,7 @@ public class StringOperators {
* substrings based on the given delimiter.
*
* @param delimiter must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(String delimiter) {
return createSplit().split(delimiter);
@@ -322,7 +322,7 @@ public class StringOperators {
* substrings based on the delimiter resulting from the referenced field..
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(Field fieldReference) {
return createSplit().split(fieldReference);
@@ -333,7 +333,7 @@ public class StringOperators {
* substrings based on a delimiter resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(AggregationExpression expression) {
return createSplit().split(expression);
@@ -347,7 +347,7 @@ public class StringOperators {
* Creates new {@link AggregationExpression} that returns the number of UTF-8 bytes in the associated string
* representation.
*
* @return new instance of {@link StrLenBytes}.
* @return
*/
public StrLenBytes length() {
return usesFieldRef() ? StrLenBytes.stringLengthOf(fieldReference) : StrLenBytes.stringLengthOf(expression);
@@ -357,7 +357,7 @@ public class StringOperators {
* Creates new {@link AggregationExpression} that returns the number of UTF-8 code points in the associated string
* representation.
*
* @return new instance of {@link StrLenCP}.
* @return
*/
public StrLenCP lengthCP() {
return usesFieldRef() ? StrLenCP.stringLengthOfCP(fieldReference) : StrLenCP.stringLengthOfCP(expression);
@@ -368,7 +368,7 @@ public class StringOperators {
* starting at a specified code point index position.
*
* @param codePointStart
* @return new instance of {@link SubstrCP}.
* @return
*/
public SubstrCP substringCP(int codePointStart) {
return substringCP(codePointStart, -1);
@@ -378,9 +378,9 @@ public class StringOperators {
* Creates new {@link AggregationExpression} that takes the associated string representation and returns a substring
* starting at a specified code point index position including the specified number of code points.
*
* @param codePointStart start point (including).
* @param codePointStart
* @param nrOfCodePoints
* @return new instance of {@link SubstrCP}.
* @return
*/
public SubstrCP substringCP(int codePointStart, int nrOfCodePoints) {
return createSubstrCP().substringCP(codePointStart, nrOfCodePoints);
@@ -541,7 +541,7 @@ public class StringOperators {
* Creates new {@link Concat}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public static Concat valueOf(String fieldReference) {
@@ -553,7 +553,7 @@ public class StringOperators {
* Creates new {@link Concat}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public static Concat valueOf(AggregationExpression expression) {
@@ -565,7 +565,7 @@ public class StringOperators {
* Creates new {@link Concat}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Concat}.
* @return
*/
public static Concat stringValue(String value) {
@@ -573,36 +573,18 @@ public class StringOperators {
return new Concat(Collections.singletonList(value));
}
/**
* Concat the value of the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Concat}.
*/
public Concat concatValueOf(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Concat(append(Fields.field(fieldReference)));
}
/**
* Concat the value resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Concat}.
*/
public Concat concatValueOf(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Concat(append(expression));
}
/**
* Concat the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Concat}.
*/
public Concat concat(String value) {
return new Concat(append(value));
}
@@ -628,7 +610,7 @@ public class StringOperators {
* Creates new {@link Substr}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Substr}.
* @return
*/
public static Substr valueOf(String fieldReference) {
@@ -640,7 +622,7 @@ public class StringOperators {
* Creates new {@link Substr}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Substr}.
* @return
*/
public static Substr valueOf(AggregationExpression expression) {
@@ -648,19 +630,10 @@ public class StringOperators {
return new Substr(Collections.singletonList(expression));
}
/**
* @param start start index (including)
* @return new instance of {@link Substr}.
*/
public Substr substring(int start) {
return substring(start, -1);
}
/**
* @param start start index (including)
* @param nrOfChars
* @return new instance of {@link Substr}.
*/
public Substr substring(int start, int nrOfChars) {
return new Substr(append(Arrays.asList(start, nrOfChars)));
}
@@ -804,7 +777,7 @@ public class StringOperators {
* Creates new {@link StrCaseCmp}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StrCaseCmp}.
* @return
*/
public static StrCaseCmp valueOf(AggregationExpression expression) {
@@ -816,7 +789,7 @@ public class StringOperators {
* Creates new {@link StrCaseCmp}.
*
* @param value must not be {@literal null}.
* @return new instance of {@link StrCaseCmp}.
* @return
*/
public static StrCaseCmp stringValue(String value) {
@@ -861,7 +834,7 @@ public class StringOperators {
* Start creating a new {@link IndexOfBytes}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link SubstringBuilder}.
* @return
*/
public static SubstringBuilder valueOf(String fieldReference) {
@@ -873,7 +846,7 @@ public class StringOperators {
* Start creating a new {@link IndexOfBytes}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SubstringBuilder}.
* @return
*/
public static SubstringBuilder valueOf(AggregationExpression expression) {
@@ -885,7 +858,7 @@ public class StringOperators {
* Optionally define the substring search start and end position.
*
* @param range must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes within(Range<Long> range) {
return new IndexOfBytes(append(AggregationUtils.toRangeValues(range)));
@@ -903,7 +876,7 @@ public class StringOperators {
* Creates a new {@link IndexOfBytes} given {@literal substring}.
*
* @param substring must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(String substring) {
return new IndexOfBytes(Arrays.asList(stringExpression, substring));
@@ -913,7 +886,7 @@ public class StringOperators {
* Creates a new {@link IndexOfBytes} given {@link AggregationExpression} that resolves to the substring.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(AggregationExpression expression) {
return new IndexOfBytes(Arrays.asList(stringExpression, expression));
@@ -923,7 +896,7 @@ public class StringOperators {
* Creates a new {@link IndexOfBytes} given {@link Field} that resolves to the substring.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IndexOfBytes}.
* @return
*/
public IndexOfBytes indexOf(Field fieldReference) {
return new IndexOfBytes(Arrays.asList(stringExpression, fieldReference));
@@ -951,7 +924,7 @@ public class StringOperators {
* Start creating a new {@link IndexOfCP}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public static SubstringBuilder valueOf(String fieldReference) {
@@ -963,7 +936,7 @@ public class StringOperators {
* Start creating a new {@link IndexOfCP}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public static SubstringBuilder valueOf(AggregationExpression expression) {
@@ -975,7 +948,7 @@ public class StringOperators {
* Optionally define the substring search start and end position.
*
* @param range must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP within(Range<Long> range) {
return new IndexOfCP(append(AggregationUtils.toRangeValues(range)));
@@ -993,7 +966,7 @@ public class StringOperators {
* Creates a new {@link IndexOfCP} given {@literal substring}.
*
* @param substring must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP indexOf(String substring) {
return new IndexOfCP(Arrays.asList(stringExpression, substring));
@@ -1003,7 +976,7 @@ public class StringOperators {
* Creates a new {@link IndexOfCP} given {@link AggregationExpression} that resolves to the substring.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link IndexOfCP}.
* @return
*/
public IndexOfCP indexOf(AggregationExpression expression) {
return new IndexOfCP(Arrays.asList(stringExpression, expression));
@@ -1041,7 +1014,7 @@ public class StringOperators {
* Start creating a new {@link Split}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public static Split valueOf(String fieldReference) {
@@ -1053,7 +1026,7 @@ public class StringOperators {
* Start creating a new {@link Split}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public static Split valueOf(AggregationExpression expression) {
@@ -1065,7 +1038,7 @@ public class StringOperators {
* Use given {@link String} as delimiter.
*
* @param delimiter must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(String delimiter) {
@@ -1077,7 +1050,7 @@ public class StringOperators {
* Use value of referenced field as delimiter.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(Field fieldReference) {
@@ -1089,7 +1062,7 @@ public class StringOperators {
* Use value resulting from {@link AggregationExpression} as delimiter.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Split}.
* @return
*/
public Split split(AggregationExpression expression) {
@@ -1118,7 +1091,7 @@ public class StringOperators {
* Creates new {@link StrLenBytes}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StrLenBytes}.
* @return
*/
public static StrLenBytes stringLengthOf(String fieldReference) {
return new StrLenBytes(Fields.field(fieldReference));
@@ -1128,7 +1101,7 @@ public class StringOperators {
* Creates new {@link StrLenBytes}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StrLenBytes}.
* @return
*/
public static StrLenBytes stringLengthOf(AggregationExpression expression) {
@@ -1157,7 +1130,7 @@ public class StringOperators {
* Creates new {@link StrLenCP}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link StrLenCP}.
* @return
*/
public static StrLenCP stringLengthOfCP(String fieldReference) {
return new StrLenCP(Fields.field(fieldReference));
@@ -1167,7 +1140,7 @@ public class StringOperators {
* Creates new {@link StrLenCP}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link StrLenCP}.
* @return
*/
public static StrLenCP stringLengthOfCP(AggregationExpression expression) {
@@ -1196,7 +1169,7 @@ public class StringOperators {
* Creates new {@link SubstrCP}.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link SubstrCP}.
* @return
*/
public static SubstrCP valueOf(String fieldReference) {
@@ -1208,7 +1181,7 @@ public class StringOperators {
* Creates new {@link SubstrCP}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link SubstrCP}.
* @return
*/
public static SubstrCP valueOf(AggregationExpression expression) {

View File

@@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mapping.PersistentPropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.DirectFieldReference;
@@ -128,7 +127,7 @@ public class TypeBasedAggregationOperationContext implements AggregationOperatio
return Fields.fields(fields.toArray(new String[0]));
}
private FieldReference getReferenceFor(Field field) {
protected FieldReference getReferenceFor(Field field) {
PersistentPropertyPath<MongoPersistentProperty> propertyPath = mappingContext
.getPersistentPropertyPath(field.getTarget(), type);

View File

@@ -0,0 +1,144 @@
/*
* Copyright 2019-2020 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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation.InheritsFieldsAggregationOperation;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Removes fields from documents.
*
* @author Christoph Strobl
* @since 3.0
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unset/">MongoDB Aggregation Framework:
* $unset</a>
*/
public class UnsetOperation implements InheritsFieldsAggregationOperation {
private final Collection<Object> fields;
/**
* Create new instance of {@link UnsetOperation}.
*
* @param fields must not be {@literal null}.
*/
public UnsetOperation(Collection<Object> fields) {
Assert.notNull(fields, "Fields must not be null!");
Assert.noNullElements(fields, "Fields must not contain null values.");
this.fields = fields;
}
/**
* Create new instance of {@link UnsetOperation}.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link UnsetOperation}.
*/
public static UnsetOperation unset(String... fields) {
return new UnsetOperation(Arrays.asList(fields));
}
/**
* Also unset the given fields.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link UnsetOperation}.
*/
public UnsetOperation and(String... fields) {
List<Object> target = new ArrayList<>(this.fields);
CollectionUtils.mergeArrayIntoCollection(fields, target);
return new UnsetOperation(target);
}
/**
* Also unset the given fields.
*
* @param fields must not be {@literal null}.
* @return new instance of {@link UnsetOperation}.
*/
public UnsetOperation and(Field... fields) {
List<Object> target = new ArrayList<>(this.fields);
CollectionUtils.mergeArrayIntoCollection(fields, target);
return new UnsetOperation(target);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation#getFields()
*/
@Override
public ExposedFields getFields() {
return ExposedFields.from();
}
Collection<String> removedFieldNames() {
List<String> fieldNames = new ArrayList<>(fields.size());
for (Object it : fields) {
if (it instanceof Field) {
fieldNames.add(((Field) it).getName());
} else {
fieldNames.add(it.toString());
}
}
return fieldNames;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {
if (fields.size() == 1) {
return new Document("$unset", computeFieldName(fields.iterator().next(), context));
}
return new Document("$unset",
fields.stream().map(it -> computeFieldName(it, context)).collect(Collectors.toList()));
}
private Object computeFieldName(Object field, AggregationOperationContext context) {
if (field instanceof Field) {
return context.getReference((Field) field).getRaw();
}
if (field instanceof AggregationExpression) {
return ((AggregationExpression) field).toDocument(context);
}
if (field instanceof String) {
return context.getReference((String) field).getRaw();
}
return field;
}
}

View File

@@ -72,7 +72,7 @@ public abstract class AbstractMongoConverter implements MongoConverter, Initiali
/**
* Registers {@link EntityInstantiators} to customize entity instantiation.
*
* @param instantiators can be {@literal null}. Uses default {@link EntityInstantiators} if so.
* @param instantiators
*/
public void setInstantiators(@Nullable EntityInstantiators instantiators) {
this.instantiators = instantiators == null ? new EntityInstantiators() : instantiators;

View File

@@ -46,7 +46,7 @@ public class CustomConversions extends MongoCustomConversions {
/**
* Creates a new {@link CustomConversions} instance registering the given converters.
*
* @param converters must not be {@literal null}.
* @param converters
*/
public CustomConversions(List<?> converters) {
super(converters);

View File

@@ -45,7 +45,7 @@ public interface DbRefResolver {
* @param property will never be {@literal null}.
* @param dbref the {@link DBRef} to resolve.
* @param callback will never be {@literal null}.
* @return can be {@literal null}.
* @return
*/
@Nullable
Object resolveDbRef(MongoPersistentProperty property, @Nullable DBRef dbref, DbRefResolverCallback callback,
@@ -58,7 +58,7 @@ public interface DbRefResolver {
* @param annotation will never be {@literal null}.
* @param entity will never be {@literal null}.
* @param id will never be {@literal null}.
* @return new instance of {@link DBRef}.
* @return
*/
default DBRef createDbRef(@Nullable org.springframework.data.mongodb.core.mapping.DBRef annotation,
MongoPersistentEntity<?> entity, Object id) {
@@ -74,7 +74,7 @@ public interface DbRefResolver {
* Actually loads the {@link DBRef} from the datasource.
*
* @param dbRef must not be {@literal null}.
* @return can be {@literal null}.
* @return
* @since 1.7
*/
@Nullable

View File

@@ -202,7 +202,7 @@ public class DefaultDbRefResolver implements DbRefResolver {
proxyFactory.addInterface(propertyType);
proxyFactory.addAdvice(interceptor);
return handler.populateId(property, dbref, proxyFactory.getProxy(LazyLoadingProxy.class.getClassLoader()));
return handler.populateId(property, dbref, proxyFactory.getProxy());
}
/**

View File

@@ -23,6 +23,7 @@ import java.util.function.UnaryOperator;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.convert.DefaultTypeMapper;
import org.springframework.data.convert.SimpleTypeInformationMapper;
@@ -41,7 +42,9 @@ import com.mongodb.DBObject;
/**
* Default implementation of {@link MongoTypeMapper} allowing configuration of the key to lookup and store type
* information in {@link Document}. The key defaults to {@link #DEFAULT_TYPE_KEY}.
* information in {@link Document}. The key defaults to {@link #DEFAULT_TYPE_KEY}. Actual type-to-{@link String}
* conversion and back is done in {@link #getTypeString(TypeInformation)} or {@link #getTypeInformation(String)}
* respectively.
*
* @author Oliver Gierke
* @author Thomas Darimont
@@ -108,7 +111,7 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<Bson> implements M
* {@link TypeInformationMapper} to map type hints.
*
* @param typeKey name of the field to read and write type hints. Can be {@literal null} to disable type hints.
* @param mappers must not be {@literal null}.
* @param mappers
*/
public DefaultMongoTypeMapper(@Nullable String typeKey, List<? extends TypeInformationMapper> mappers) {
this(typeKey, new DocumentTypeAliasAccessor(typeKey), null, mappers);

View File

@@ -70,10 +70,10 @@ class DocumentAccessor {
/**
* Puts the given value into the backing {@link Document} based on the coordinates defined through the given
* {@link MongoPersistentProperty}. By default this will be the plain field name. But field names might also consist
* of path traversals so we might need to create intermediate {@link Document}s.
* of path traversals so we might need to create intermediate {@link BasicDocument}s.
*
* @param prop must not be {@literal null}.
* @param value can be {@literal null}.
* @param value
*/
public void put(MongoPersistentProperty prop, @Nullable Object value) {
@@ -106,7 +106,7 @@ class DocumentAccessor {
* a path expression in the field name metadata.
*
* @param property must not be {@literal null}.
* @return can be {@literal null}.
* @return
*/
@Nullable
public Object get(MongoPersistentProperty property) {
@@ -150,7 +150,7 @@ class DocumentAccessor {
* {@link MongoPersistentProperty}.
*
* @param property must not be {@literal null}.
* @return {@literal true} if no non {@literal null} value present.
* @return
*/
@SuppressWarnings("unchecked")
public boolean hasValue(MongoPersistentProperty property) {
@@ -203,7 +203,7 @@ class DocumentAccessor {
* Returns the given source object as map, i.e. {@link Document}s and maps as is or {@literal null} otherwise.
*
* @param source can be {@literal null}.
* @return can be {@literal null}.
* @return
*/
@Nullable
@SuppressWarnings("unchecked")

View File

@@ -91,7 +91,7 @@ abstract class GeoConverters {
/**
* Returns the geo converters to be registered.
*
* @return never {@literal null}.
* @return
*/
@SuppressWarnings("unchecked")
public static Collection<? extends Object> getConvertersToRegister() {
@@ -817,8 +817,8 @@ abstract class GeoConverters {
/**
* Converts a coordinate pairs nested in in {@link BasicDBList} into {@link GeoJsonPoint}s.
*
* @param listOfCoordinatePairs must not be {@literal null}.
* @return never {@literal null}.
* @param listOfCoordinatePairs
* @return
* @since 1.7
*/
@SuppressWarnings("unchecked")
@@ -841,8 +841,8 @@ abstract class GeoConverters {
/**
* Converts a coordinate pairs nested in in {@link BasicDBList} into {@link GeoJsonPolygon}.
*
* @param dbList must not be {@literal null}.
* @return never {@literal null}.
* @param dbList
* @return
* @since 1.7
*/
static GeoJsonPolygon toGeoJsonPolygon(List dbList) {

View File

@@ -90,9 +90,8 @@ import com.mongodb.DBRef;
* @author Christoph Strobl
* @author Jordi Llach
* @author Mark Paluch
* @author Heesu Jung
*/
public class MappingMongoConverter extends AbstractMongoConverter implements ApplicationContextAware {
public class MappingMongoConverter extends AbstractMongoConverter implements ApplicationContextAware, ValueResolver {
private static final String INCOMPATIBLE_TYPES = "Cannot convert %1$s of type %2$s into an instance of %3$s! Implement a custom Converter<%2$s, %3$s> and register it with the CustomConversions. Parent object was: %4$s";
private static final String INVALID_TYPE_TO_READ = "Expected to read Document %s into type %s but didn't find a PersistentEntity for the latter!";
@@ -132,8 +131,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
this.idMapper = new QueryMapper(this);
this.spELContext = new SpELContext(DocumentPropertyAccessor.INSTANCE);
this.dbRefProxyHandler = new DefaultDbRefProxyHandler(spELContext, mappingContext,
MappingMongoConverter.this::getValueInternal);
this.dbRefProxyHandler = new DefaultDbRefProxyHandler(spELContext, mappingContext, MappingMongoConverter.this);
}
/**
@@ -228,9 +226,11 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
@Nullable
@SuppressWarnings("unchecked")
private <S extends Object> S read(TypeInformation<S> type, Bson bson, ObjectPath path) {
private <S extends Object> S read(TypeInformation<S> type, @Nullable Bson bson, ObjectPath path) {
Assert.notNull(bson, "Bson must not be null!");
if (null == bson) {
return null;
}
TypeInformation<? extends S> typeToUse = typeMapper.readType(bson, type);
Class<? extends S> rawType = typeToUse.getType();
@@ -431,7 +431,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
SpELExpressionEvaluator evaluator) {
return new DefaultDbRefResolverCallback(documentAccessor.getDocument(), currentPath, evaluator,
MappingMongoConverter.this::getValueInternal);
MappingMongoConverter.this);
}
private void readAssociation(Association<MongoPersistentProperty> association, PersistentPropertyAccessor<?> accessor,
@@ -473,7 +473,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
* Root entry method into write conversion. Adds a type discriminator to the {@link Document}. Shouldn't be called for
* nested conversions.
*
* @see org.springframework.data.mongodb.core.convert.MongoWriter#write(java.lang.Object, java.lang.Object)
* @see org.springframework.data.mongodb.core.convert.MongoWriter#write(java.lang.Object, com.mongodb.Document)
*/
public void write(Object obj, Bson bson) {
@@ -1047,7 +1047,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.convert.ValueResolver#getValueInternal(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty, com.mongodb.Document, org.springframework.data.mapping.model.SpELExpressionEvaluator, java.lang.Object)
*/
@Nullable
@Override
public Object getValueInternal(MongoPersistentProperty prop, Bson bson, SpELExpressionEvaluator evaluator,
ObjectPath path) {
return new MongoDbPropertyValueProvider(bson, evaluator, path).getPropertyValue(prop);
@@ -1261,16 +1261,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
}
if (conversions.isSimpleType(obj.getClass())) {
Class<?> conversionTargetType;
if (typeInformation != null && conversions.isSimpleType(typeInformation.getType())) {
conversionTargetType = typeInformation.getType();
} else {
conversionTargetType = Object.class;
}
return getPotentiallyConvertedSimpleWrite(obj, conversionTargetType);
// Doesn't need conversion
return getPotentiallyConvertedSimpleWrite(obj,
typeInformation != null ? typeInformation.getType() : Object.class);
}
if (obj instanceof List) {
@@ -1498,7 +1491,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
}
DbRefResolverCallback callback = new DefaultDbRefResolverCallback(accessor.getDocument(), path, evaluator,
MappingMongoConverter.this::getValueInternal);
MappingMongoConverter.this);
DBRef dbref = rawRefValue instanceof DBRef ? (DBRef) rawRefValue : null;
return (T) dbRefResolver.resolveDbRef(property, dbref, callback, dbRefProxyHandler);
@@ -1580,7 +1573,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
@Nullable
private <T> T readAndConvertDBRef(@Nullable DBRef dbref, TypeInformation<?> type, ObjectPath path,
@Nullable Class<?> rawType) {
final Class<?> rawType) {
List<T> result = bulkReadAndConvertDBRefs(Collections.singletonList(dbref), type, path, rawType);
return CollectionUtils.isEmpty(result) ? null : result.iterator().next();
@@ -1603,7 +1596,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
@SuppressWarnings("unchecked")
private <T> List<T> bulkReadAndConvertDBRefs(List<DBRef> dbrefs, TypeInformation<?> type, ObjectPath path,
@Nullable Class<?> rawType) {
final Class<?> rawType) {
if (CollectionUtils.isEmpty(dbrefs)) {
return Collections.emptyList();
@@ -1618,19 +1611,16 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
for (Document document : referencedRawDocuments) {
T target = null;
if (document != null) {
maybeEmitEvent(
new AfterLoadEvent<>(document, (Class<T>) (rawType != null ? rawType : Object.class), collectionName));
target = (T) read(type, document, path);
maybeEmitEvent(new AfterLoadEvent<>(document, (Class<T>) rawType, collectionName));
}
final T target = (T) read(type, document, path);
targeList.add(target);
if (target != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, target, collectionName));
}
targeList.add(target);
}
return targeList;

View File

@@ -119,8 +119,8 @@ public interface MongoConverter
/**
* Converts the given raw id value into either {@link ObjectId} or {@link String}.
*
* @param id can be {@literal null}.
* @param targetType must not be {@literal null}.
* @param id
* @param targetType
* @return {@literal null} if source {@literal id} is already {@literal null}.
* @since 2.2
*/

View File

@@ -110,7 +110,7 @@ abstract class MongoConverters {
INSTANCE;
public String convert(ObjectId id) {
return id == null ? null : id.toString();
return id.toString();
}
}
@@ -136,7 +136,7 @@ abstract class MongoConverters {
INSTANCE;
public BigInteger convert(ObjectId source) {
return source == null ? null : new BigInteger(source.toString(), 16);
return new BigInteger(source.toString(), 16);
}
}
@@ -149,7 +149,7 @@ abstract class MongoConverters {
INSTANCE;
public ObjectId convert(BigInteger source) {
return source == null ? null : new ObjectId(source.toString(16));
return new ObjectId(source.toString(16));
}
}
@@ -157,7 +157,7 @@ abstract class MongoConverters {
INSTANCE;
public String convert(BigDecimal source) {
return source == null ? null : source.toString();
return source.toString();
}
}
@@ -168,7 +168,7 @@ abstract class MongoConverters {
INSTANCE;
public Decimal128 convert(BigDecimal source) {
return source == null ? null : new Decimal128(source);
return new Decimal128(source);
}
}
@@ -195,7 +195,7 @@ abstract class MongoConverters {
INSTANCE;
public String convert(BigInteger source) {
return source == null ? null : source.toString();
return source.toString();
}
}
@@ -211,7 +211,7 @@ abstract class MongoConverters {
INSTANCE;
public String convert(URL source) {
return source == null ? null : source.toString();
return source.toString();
}
}
@@ -224,7 +224,7 @@ abstract class MongoConverters {
public URL convert(String source) {
try {
return source == null ? null : new URL(source);
return new URL(source);
} catch (MalformedURLException e) {
throw new ConversionFailedException(SOURCE, TARGET, source, e);
}
@@ -238,11 +238,6 @@ abstract class MongoConverters {
@Override
public String convert(Document source) {
if (source == null) {
return null;
}
return source.toJson();
}
}
@@ -258,7 +253,7 @@ abstract class MongoConverters {
@Override
public String convert(Term source) {
return source == null ? null : source.getFormatted();
return source.getFormatted();
}
}
@@ -273,7 +268,7 @@ abstract class MongoConverters {
@Override
public NamedMongoScript convert(Document source) {
if (source == null) {
if(source.isEmpty()) {
return null;
}
@@ -295,10 +290,6 @@ abstract class MongoConverters {
@Override
public Document convert(NamedMongoScript source) {
if (source == null) {
return new Document();
}
Document document = new Document();
document.put("_id", source.getName());
@@ -325,7 +316,7 @@ abstract class MongoConverters {
*/
@Override
public String convert(Currency source) {
return source == null ? null : source.getCurrencyCode();
return source.getCurrencyCode();
}
}
@@ -461,7 +452,7 @@ abstract class MongoConverters {
@Override
public AtomicLong convert(Long source) {
return source != null ? new AtomicLong(source) : null;
return new AtomicLong(source);
}
}
@@ -477,7 +468,7 @@ abstract class MongoConverters {
@Override
public AtomicInteger convert(Integer source) {
return source != null ? new AtomicInteger(source) : null;
return new AtomicInteger(source);
}
}
@@ -492,7 +483,6 @@ abstract class MongoConverters {
INSTANCE;
@Nullable
@Override
public byte[] convert(Binary source) {
return source.getData();
@@ -510,7 +500,6 @@ abstract class MongoConverters {
INSTANCE;
@Nullable
@Override
public Instant convert(BsonTimestamp source) {
return Instant.ofEpochSecond(source.getTime(), 0);

View File

@@ -24,6 +24,7 @@ import org.bson.BsonValue;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Example;
@@ -174,7 +175,7 @@ public class QueryMapper {
}
Document mappedSort = new Document();
for (Map.Entry<String, Object> entry : BsonUtils.asMap(sortObject).entrySet()) {
for(Map.Entry<String,Object> entry : BsonUtils.asMap(sortObject).entrySet()) {
Field field = createPropertyField(entity, entry.getKey(), mappingContext);
mappedSort.put(field.getMappedKey(), entry.getValue());
@@ -419,7 +420,7 @@ public class QueryMapper {
return false;
}
Class<?> type = value.getClass();
Class<? extends Object> type = value.getClass();
MongoPersistentProperty property = documentField.getProperty();
if (property.getActualType().isAssignableFrom(type)) {
@@ -443,7 +444,7 @@ public class QueryMapper {
protected Object convertSimpleOrDocument(Object source, @Nullable MongoPersistentEntity<?> entity) {
if (source instanceof Example) {
return exampleMapper.getMappedExample((Example<?>) source, entity);
return exampleMapper.getMappedExample((Example) source, entity);
}
if (source instanceof List) {
@@ -816,7 +817,7 @@ public class QueryMapper {
protected final String name;
/**
* Creates a new {@link Field} without meta-information but the given name.
* Creates a new {@link DocumentField} without meta-information but the given name.
*
* @param name must not be {@literal null} or empty.
*/
@@ -827,7 +828,7 @@ public class QueryMapper {
}
/**
* Returns a new {@link Field} with the given name.
* Returns a new {@link DocumentField} with the given name.
*
* @param name must not be {@literal null} or empty.
* @return
@@ -922,8 +923,6 @@ public class QueryMapper {
*/
protected static class MetadataBackedField extends Field {
private static final Pattern POSITIONAL_PARAMETER_PATTERN = Pattern.compile("\\.\\$(\\[.*?\\])?|\\.\\d+");
private static final Pattern DOT_POSITIONAL_PATTERN = Pattern.compile("\\.\\d+");
private static final String INVALID_ASSOCIATION_REFERENCE = "Invalid path reference %s! Associations can only be pointed to directly or via their id property!";
private final MongoPersistentEntity<?> entity;
@@ -965,7 +964,7 @@ public class QueryMapper {
this.entity = entity;
this.mappingContext = context;
this.path = getPath(removePlaceholders(POSITIONAL_PARAMETER_PATTERN, name), property);
this.path = getPath(name);
this.property = path == null ? property : path.getLeafProperty();
this.association = findAssociation();
}
@@ -1073,22 +1072,16 @@ public class QueryMapper {
}
/**
* Returns the {@link PersistentPropertyPath} for the given {@code pathExpression}.
* Returns the {@link PersistentPropertyPath} for the given <code>pathExpression</code>.
*
* @param pathExpression
* @return
*/
@Nullable
private PersistentPropertyPath<MongoPersistentProperty> getPath(String pathExpression,
@Nullable MongoPersistentProperty sourceProperty) {
private PersistentPropertyPath<MongoPersistentProperty> getPath(String pathExpression) {
String rawPath = removePlaceholders(POSITIONAL_OPERATOR,
removePlaceholders(DOT_POSITIONAL_PATTERN, pathExpression));
if (sourceProperty != null && sourceProperty.getOwner().equals(entity)) {
return mappingContext
.getPersistentPropertyPath(PropertyPath.from(sourceProperty.getName(), entity.getTypeInformation()));
}
String rawPath = pathExpression.replaceAll("\\.\\d+", "") //
.replaceAll(POSITIONAL_OPERATOR.pattern(), "");
PropertyPath path = forName(rawPath);
if (path == null || isPathToJavaLangClassProperty(path)) {
@@ -1165,7 +1158,7 @@ public class QueryMapper {
* @return
*/
protected Converter<MongoPersistentProperty, String> getPropertyConverter() {
return new PositionParameterRetainingPropertyKeyConverter(name, mappingContext);
return new PositionParameterRetainingPropertyKeyConverter(name);
}
/**
@@ -1176,15 +1169,7 @@ public class QueryMapper {
* @since 1.7
*/
protected Converter<MongoPersistentProperty, String> getAssociationConverter() {
return new AssociationConverter(name, getAssociation());
}
protected MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> getMappingContext() {
return mappingContext;
}
private static String removePlaceholders(Pattern pattern, String raw) {
return pattern.matcher(raw).replaceAll("");
return new AssociationConverter(getAssociation());
}
/**
@@ -1195,9 +1180,8 @@ public class QueryMapper {
private final KeyMapper keyMapper;
public PositionParameterRetainingPropertyKeyConverter(String rawKey,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> ctx) {
this.keyMapper = new KeyMapper(rawKey, ctx);
public PositionParameterRetainingPropertyKeyConverter(String rawKey) {
this.keyMapper = new KeyMapper(rawKey);
}
/*
@@ -1239,8 +1223,7 @@ public class QueryMapper {
private final Iterator<String> iterator;
public KeyMapper(String key,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
public KeyMapper(String key) {
this.iterator = Arrays.asList(key.split("\\.")).iterator();
this.iterator.next();
@@ -1260,7 +1243,6 @@ public class QueryMapper {
while (inspect) {
String partial = iterator.next();
boolean isPositional = (isPositionalParameter(partial) && (property.isMap() || property.isCollectionLike()));
if (isPositional) {
@@ -1273,7 +1255,7 @@ public class QueryMapper {
return mappedName.toString();
}
static boolean isPositionalParameter(String partial) {
private static boolean isPositionalParameter(String partial) {
if ("$".equals(partial)) {
return true;
@@ -1301,7 +1283,6 @@ public class QueryMapper {
*/
protected static class AssociationConverter implements Converter<MongoPersistentProperty, String> {
private final String name;
private final MongoPersistentProperty property;
private boolean associationFound;
@@ -1310,11 +1291,10 @@ public class QueryMapper {
*
* @param association must not be {@literal null}.
*/
public AssociationConverter(String name, Association<MongoPersistentProperty> association) {
public AssociationConverter(Association<MongoPersistentProperty> association) {
Assert.notNull(association, "Association must not be null!");
this.property = association.getInverse();
this.name = name;
}
/*
@@ -1332,12 +1312,6 @@ public class QueryMapper {
associationFound = true;
}
if (associationFound) {
if (name.endsWith("$") && property.isCollectionLike()) {
return source.getFieldName() + ".$";
}
}
return source.getFieldName();
}
}

View File

@@ -272,7 +272,6 @@ public class UpdateMapper extends QueryMapper {
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
*/
private static class MetadataBackedUpdateField extends MetadataBackedField {
@@ -290,7 +289,7 @@ public class UpdateMapper extends QueryMapper {
public MetadataBackedUpdateField(MongoPersistentEntity<?> entity, String key,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
super(key, entity, mappingContext);
super(key.replaceAll("\\.\\$(\\[.*\\])?", ""), entity, mappingContext);
this.key = key;
}
@@ -309,7 +308,7 @@ public class UpdateMapper extends QueryMapper {
*/
@Override
protected Converter<MongoPersistentProperty, String> getPropertyConverter() {
return new PositionParameterRetainingPropertyKeyConverter(key, getMappingContext());
return new PositionParameterRetainingPropertyKeyConverter(key);
}
/*
@@ -318,7 +317,7 @@ public class UpdateMapper extends QueryMapper {
*/
@Override
protected Converter<MongoPersistentProperty, String> getAssociationConverter() {
return new UpdateAssociationConverter(getMappingContext(), getAssociation(), key);
return new UpdateAssociationConverter(getAssociation(), key);
}
/**
@@ -335,12 +334,10 @@ public class UpdateMapper extends QueryMapper {
*
* @param association must not be {@literal null}.
*/
public UpdateAssociationConverter(
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext,
Association<MongoPersistentProperty> association, String key) {
public UpdateAssociationConverter(Association<MongoPersistentProperty> association, String key) {
super(key, association);
this.mapper = new KeyMapper(key, mappingContext);
super(association);
this.mapper = new KeyMapper(key);
}
/*

View File

@@ -19,14 +19,12 @@ import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.mapping.model.SpELExpressionEvaluator;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
/**
* Internal API to trigger the resolution of properties.
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
*/
interface ValueResolver {
@@ -37,9 +35,9 @@ interface ValueResolver {
* @param prop
* @param bson
* @param evaluator
* @param path
* @param parent
* @return
*/
@Nullable
Object getValueInternal(MongoPersistentProperty prop, Bson bson, SpELExpressionEvaluator evaluator, ObjectPath path);
Object getValueInternal(MongoPersistentProperty prop, Bson bson, SpELExpressionEvaluator evaluator,
ObjectPath path);
}

View File

@@ -16,7 +16,7 @@
package org.springframework.data.mongodb.core.geo;
/**
* Interface definition for structures defined in <a href="https://geojson.org/>GeoJSON</a> format.
* Interface definition for structures defined in GeoJSON ({@link https://geojson.org/}) format.
*
* @author Christoph Strobl
* @since 1.7

View File

@@ -38,7 +38,7 @@ public class GeoJsonGeometryCollection implements GeoJson<Iterable<GeoJson<?>>>
/**
* Creates a new {@link GeoJsonGeometryCollection} for the given {@link GeoJson} instances.
*
* @param geometries must not be {@literal null}.
* @param geometries
*/
public GeoJsonGeometryCollection(List<GeoJson<?>> geometries) {

View File

@@ -58,7 +58,7 @@ public class Sphere implements Shape {
/**
* Creates a Sphere around the given center {@link Point} with the given radius.
*
* @param center must not be {@literal null}.
* @param center
* @param radius
*/
public Sphere(Point center, double radius) {
@@ -68,7 +68,7 @@ public class Sphere implements Shape {
/**
* Creates a Sphere from the given {@link Circle}.
*
* @param circle must not be {@literal null}.
* @param circle
*/
public Sphere(Circle circle) {
this(circle.getCenter(), circle.getRadius());
@@ -86,7 +86,7 @@ public class Sphere implements Shape {
/**
* Returns the radius of the {@link Circle}.
*
* @return never {@literal null}.
* @return
*/
public Distance getRadius() {
return radius;
@@ -136,7 +136,7 @@ public class Sphere implements Shape {
* Returns the {@link Shape} as a list of usually {@link Double} or {@link List}s of {@link Double}s. Wildcard bound
* to allow implementations to return a more concrete element type.
*
* @return never {@literal null}.
* @return
*/
public List<? extends Object> asList() {
return Arrays.asList(Arrays.asList(center.getX(), center.getY()), this.radius.getValue());
@@ -145,7 +145,7 @@ public class Sphere implements Shape {
/**
* Returns the command to be used to create the {@literal $within} criterion.
*
* @return never {@literal null}.
* @return
*/
public String getCommand() {
return COMMAND;

View File

@@ -74,7 +74,7 @@ public @interface CompoundIndex {
* }
* </pre>
*
* @return empty String by default.
* @return
*/
String def() default "";
@@ -82,13 +82,13 @@ public @interface CompoundIndex {
* It does not actually make sense to use that attribute as the direction has to be defined in the {@link #def()}
* attribute actually.
*
* @return {@link IndexDirection#ASCENDING} by default.
* @return
*/
@Deprecated
IndexDirection direction() default IndexDirection.ASCENDING;
/**
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-unique/">https://docs.mongodb.org/manual/core/index-unique/</a>
*/
@@ -97,14 +97,14 @@ public @interface CompoundIndex {
/**
* If set to true index will skip over any document that is missing the indexed field.
*
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-sparse/">https://docs.mongodb.org/manual/core/index-sparse/</a>
*/
boolean sparse() default false;
/**
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping">https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping</a>
* @deprecated since 2.1. No longer supported by MongoDB as of server version 3.0.
@@ -148,7 +148,7 @@ public @interface CompoundIndex {
* db.hybrid.createIndex( { h1: 1, h2: 1 } , { name: "compound_index" } )
* </pre>
*
* @return empty String by default.
* @return
*/
String name() default "";
@@ -156,7 +156,7 @@ public @interface CompoundIndex {
* If set to {@literal true} then MongoDB will ignore the given index name and instead generate a new name. Defaults
* to {@literal false}.
*
* @return {@literal false} by default
* @return
* @since 1.5
*/
boolean useGeneratedName() default false;
@@ -164,7 +164,7 @@ public @interface CompoundIndex {
/**
* If {@literal true} the index will be created in the background.
*
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/indexes/#background-construction">https://docs.mongodb.org/manual/core/indexes/#background-construction</a>
*/

View File

@@ -72,7 +72,7 @@ public @interface GeoSpatialIndexed {
* </code>
* </pre>
*
* @return empty {@link String} by default.
* @return
*/
String name() default "";
@@ -80,7 +80,7 @@ public @interface GeoSpatialIndexed {
* If set to {@literal true} then MongoDB will ignore the given index name and instead generate a new name. Defaults
* to {@literal false}.
*
* @return {@literal false} by default.
* @return
* @since 1.5
*/
boolean useGeneratedName() default false;
@@ -88,21 +88,21 @@ public @interface GeoSpatialIndexed {
/**
* Minimum value for indexed values.
*
* @return {@literal -180} by default.
* @return
*/
int min() default -180;
/**
* Maximum value for indexed values.
*
* @return {@literal +180} by default.
* @return
*/
int max() default 180;
/**
* Bits of precision for boundary calculations.
*
* @return {@literal 26} by default.
* @return
*/
int bits() default 26;
@@ -110,7 +110,7 @@ public @interface GeoSpatialIndexed {
* The type of the geospatial index. Default is {@link GeoSpatialIndexType#GEO_2D}
*
* @since 1.4
* @return {@link GeoSpatialIndexType#GEO_2D} by default.
* @return
*/
GeoSpatialIndexType type() default GeoSpatialIndexType.GEO_2D;
@@ -118,7 +118,7 @@ public @interface GeoSpatialIndexed {
* The bucket size for {@link GeoSpatialIndexType#GEO_HAYSTACK} indexes, in coordinate units.
*
* @since 1.4
* @return {@literal 1.0} by default.
* @return
*/
double bucketSize() default 1.0;
@@ -126,7 +126,7 @@ public @interface GeoSpatialIndexed {
* The name of the additional field to use for {@link GeoSpatialIndexType#GEO_HAYSTACK} indexes
*
* @since 1.4
* @return empty {@link String} by default.
* @return
*/
String additionalField() default "";
}

View File

@@ -59,7 +59,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param name must not be {@literal null} or empty.
* @return this.
* @return
*/
public GeospatialIndex named(String name) {
@@ -69,7 +69,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param min
* @return this.
* @return
*/
public GeospatialIndex withMin(int min) {
this.min = Integer.valueOf(min);
@@ -78,7 +78,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param max
* @return this.
* @return
*/
public GeospatialIndex withMax(int max) {
this.max = Integer.valueOf(max);
@@ -87,7 +87,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param bits
* @return this.
* @return
*/
public GeospatialIndex withBits(int bits) {
this.bits = Integer.valueOf(bits);
@@ -96,7 +96,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param type must not be {@literal null}.
* @return this.
* @return
*/
public GeospatialIndex typed(GeoSpatialIndexType type) {
@@ -108,7 +108,7 @@ public class GeospatialIndex implements IndexDefinition {
/**
* @param bucketSize
* @return this.
* @return
*/
public GeospatialIndex withBucketSize(double bucketSize) {
this.bucketSize = bucketSize;
@@ -116,8 +116,8 @@ public class GeospatialIndex implements IndexDefinition {
}
/**
* @param fieldName
* @return this.
* @param fieldName.
* @return
*/
public GeospatialIndex withAdditionalField(String fieldName) {
this.additionalField = fieldName;
@@ -128,7 +128,7 @@ public class GeospatialIndex implements IndexDefinition {
* Only index the documents in a collection that meet a specified {@link IndexFilter filter expression}.
*
* @param filter can be {@literal null}.
* @return this.
* @return
* @see <a href=
* "https://docs.mongodb.com/manual/core/index-partial/">https://docs.mongodb.com/manual/core/index-partial/</a>
* @since 1.10
@@ -146,7 +146,7 @@ public class GeospatialIndex implements IndexDefinition {
* index.
*
* @param collation can be {@literal null}.
* @return this.
* @return
* @since 2.0
*/
public GeospatialIndex collation(@Nullable Collation collation) {
@@ -155,11 +155,6 @@ public class GeospatialIndex implements IndexDefinition {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexDefinition#getIndexKeys()
*/
@Override
public Document getIndexKeys() {
Document document = new Document();
@@ -189,11 +184,6 @@ public class GeospatialIndex implements IndexDefinition {
return document;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexDefinition#getIndexOptions()
*/
@Override
public Document getIndexOptions() {
Document document = new Document();

View File

@@ -40,7 +40,7 @@ public class HashedIndex implements IndexDefinition {
* Creates a new {@link HashedIndex} for the given field.
*
* @param field must not be {@literal null} nor empty.
* @return new instance of {@link HashedIndex}.
* @return
*/
public static HashedIndex hashed(String field) {
return new HashedIndex(field);

View File

@@ -73,7 +73,7 @@ public class Index implements IndexDefinition {
/**
* Reject all documents that contain a duplicate value for the indexed field.
*
* @return this.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-unique/">https://docs.mongodb.org/manual/core/index-unique/</a>
*/
@@ -85,7 +85,7 @@ public class Index implements IndexDefinition {
/**
* Skip over any document that is missing the indexed field.
*
* @return this.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-sparse/">https://docs.mongodb.org/manual/core/index-sparse/</a>
*/
@@ -97,7 +97,7 @@ public class Index implements IndexDefinition {
/**
* Build the index in background (non blocking).
*
* @return this.
* @return
* @since 1.5
*/
public Index background() {
@@ -110,7 +110,7 @@ public class Index implements IndexDefinition {
* Specifies TTL in seconds.
*
* @param value
* @return this.
* @return
* @since 1.5
*/
public Index expire(long value) {
@@ -135,8 +135,8 @@ public class Index implements IndexDefinition {
* Specifies TTL with given {@link TimeUnit}.
*
* @param value
* @param unit must not be {@literal null}.
* @return this.
* @param unit
* @return
* @since 1.5
*/
public Index expire(long value, TimeUnit unit) {
@@ -150,7 +150,7 @@ public class Index implements IndexDefinition {
* Only index the documents in a collection that meet a specified {@link IndexFilter filter expression}.
*
* @param filter can be {@literal null}.
* @return this.
* @return
* @see <a href=
* "https://docs.mongodb.com/manual/core/index-partial/">https://docs.mongodb.com/manual/core/index-partial/</a>
* @since 1.10
@@ -168,7 +168,7 @@ public class Index implements IndexDefinition {
* index.
*
* @param collation can be {@literal null}.
* @return this.
* @return
* @since 2.0
*/
public Index collation(@Nullable Collation collation) {
@@ -192,10 +192,6 @@ public class Index implements IndexDefinition {
return document;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexDefinition#getIndexOptions()
*/
public Document getIndexOptions() {
Document document = new Document();

View File

@@ -24,17 +24,7 @@ import org.bson.Document;
*/
public interface IndexDefinition {
/**
* Get the {@link Document} containing properties covered by the index.
*
* @return never {@literal null}.
*/
Document getIndexKeys();
/**
* Get the index properties such as {@literal unique},...
*
* @return never {@literal null}.
*/
Document getIndexOptions();
}

View File

@@ -81,7 +81,7 @@ public final class IndexField {
* Creates a geo {@link IndexField} for the given key.
*
* @param key must not be {@literal null} or empty.
* @return new instance of {@link IndexField}.
* @return
*/
public static IndexField geo(String key) {
return new IndexField(key, null, Type.GEO);

View File

@@ -29,7 +29,7 @@ public interface IndexFilter {
/**
* Get the raw (unmapped) filter expression.
*
* @return never {@literal null}.
* @return
*/
Document getFilterObject();

View File

@@ -68,8 +68,8 @@ public class IndexInfo {
/**
* Creates new {@link IndexInfo} parsing required properties from the given {@literal sourceDocument}.
*
* @param sourceDocument never {@literal null}.
* @return new instance of {@link IndexInfo}.
* @param sourceDocument
* @return
* @since 1.10
*/
public static IndexInfo indexInfoOf(Document sourceDocument) {
@@ -135,7 +135,7 @@ public class IndexInfo {
}
/**
* @param sourceDocument never {@literal null}.
* @param sourceDocument
* @return the {@link String} representation of the partial filter {@link Document}.
* @since 2.1.11
*/

View File

@@ -52,7 +52,7 @@ public interface IndexResolver {
* Find and create {@link IndexDefinition}s for properties of given {@link TypeInformation}. {@link IndexDefinition}s
* are created for properties and types with {@link Indexed}, {@link CompoundIndexes} or {@link GeoSpatialIndexed}.
*
* @param typeInformation must not be {@literal null}.
* @param typeInformation
* @return Empty {@link Iterable} in case no {@link IndexDefinition} could be resolved for type.
*/
Iterable<? extends IndexDefinition> resolveIndexFor(TypeInformation<?> typeInformation);
@@ -61,7 +61,7 @@ public interface IndexResolver {
* Find and create {@link IndexDefinition}s for properties of given {@link TypeInformation}. {@link IndexDefinition}s
* are created for properties and types with {@link Indexed}, {@link CompoundIndexes} or {@link GeoSpatialIndexed}.
*
* @param entityType must not be {@literal null}.
* @param entityType
* @return Empty {@link Iterable} in case no {@link IndexDefinition} could be resolved for type.
* @see 2.2
*/

View File

@@ -39,30 +39,25 @@ public @interface Indexed {
/**
* If set to true reject all documents that contain a duplicate value for the indexed field.
*
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-unique/">https://docs.mongodb.org/manual/core/index-unique/</a>
*/
boolean unique() default false;
/**
* The index sort direction.
*
* @return {@link IndexDirection#ASCENDING} by default.
*/
IndexDirection direction() default IndexDirection.ASCENDING;
/**
* If set to true index will skip over any document that is missing the indexed field.
*
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-sparse/">https://docs.mongodb.org/manual/core/index-sparse/</a>
*/
boolean sparse() default false;
/**
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping">https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping</a>
* @deprecated since 2.1. No longer supported by MongoDB as of server version 3.0.
@@ -110,7 +105,7 @@ public @interface Indexed {
* </code>
* </pre>
*
* @return empty String by default.
* @return
*/
String name() default "";
@@ -118,7 +113,7 @@ public @interface Indexed {
* If set to {@literal true} then MongoDB will ignore the given index name and instead generate a new name. Defaults
* to {@literal false}.
*
* @return {@literal false} by default.
* @return
* @since 1.5
*/
boolean useGeneratedName() default false;
@@ -126,7 +121,7 @@ public @interface Indexed {
/**
* If {@literal true} the index will be created in the background.
*
* @return {@literal false} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/core/indexes/#background-construction">https://docs.mongodb.org/manual/core/indexes/#background-construction</a>
*/
@@ -135,7 +130,7 @@ public @interface Indexed {
/**
* Configures the number of seconds after which the collection should expire. Defaults to -1 for no expiry.
*
* @return {@literal -1} by default.
* @return
* @see <a href=
* "https://docs.mongodb.org/manual/tutorial/expire-data/">https://docs.mongodb.org/manual/tutorial/expire-data/</a>
*/

View File

@@ -77,7 +77,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener<Ma
* {@link MongoDbFactory}.
*
* @param mappingContext must not be {@literal null}.
* @param indexOperationsProvider must not be {@literal null}.
* @param mongoDbFactory must not be {@literal null}.
* @param indexResolver must not be {@literal null}.
*/
public MongoPersistentEntityIndexCreator(MongoMappingContext mappingContext,

View File

@@ -140,7 +140,7 @@ public class BasicMongoPersistentEntity<T> extends BasicPersistentEntity<T, Mong
@Override
public org.springframework.data.mongodb.core.query.Collation getCollation() {
Object collationValue = collationExpression != null ? collationExpression.getValue(getEvaluationContext(null), String.class)
Object collationValue = collationExpression != null ? expression.getValue(getEvaluationContext(null), String.class)
: this.collation;
if (collationValue == null) {
@@ -232,7 +232,7 @@ public class BasicMongoPersistentEntity<T> extends BasicPersistentEntity<T, Mong
* ambiguity a @see {@link MappingException} is thrown.
*
* @param property - the new id property candidate
* @return can be {@literal null}.
* @return
*/
@Override
protected MongoPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(MongoPersistentProperty property) {
@@ -284,7 +284,7 @@ public class BasicMongoPersistentEntity<T> extends BasicPersistentEntity<T, Mong
* {@link LiteralExpression} (indicating that no subsequent evaluation is necessary).
*
* @param potentialExpression can be {@literal null}
* @return can be {@literal null}.
* @return
*/
@Nullable
private static Expression detectExpression(@Nullable String potentialExpression) {

View File

@@ -67,10 +67,10 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
/**
* Creates a new {@link BasicMongoPersistentProperty}.
*
* @param property the source property.
* @param owner the owing entity.
* @param simpleTypeHolder must not be {@literal null}.
* @param fieldNamingStrategy can be {@literal null}.
* @param property
* @param owner
* @param simpleTypeHolder
* @param fieldNamingStrategy
*/
public BasicMongoPersistentProperty(Property property, MongoPersistentEntity<?> owner,
SimpleTypeHolder simpleTypeHolder, @Nullable FieldNamingStrategy fieldNamingStrategy) {
@@ -79,14 +79,8 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
this.fieldNamingStrategy = fieldNamingStrategy == null ? PropertyNameFieldNamingStrategy.INSTANCE
: fieldNamingStrategy;
if (isIdProperty() && hasExplicitFieldName()) {
String annotatedName = getAnnotatedFieldName();
if (!ID_FIELD_NAME.equals(annotatedName)) {
LOG.warn(
"Customizing field name for id property '{}.{}' is not allowed! Custom name ('{}') will not be considered!",
owner.getName(), getName(), annotatedName);
}
if (isIdProperty() && getFieldName() != ID_FIELD_NAME) {
LOG.warn("Customizing field name for id property not allowed! Custom name will not be considered!");
}
}
@@ -173,11 +167,6 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
FieldType fieldType = fieldAnnotation.targetType();
if (fieldType == FieldType.IMPLICIT) {
if (isEntity()) {
return org.bson.Document.class;
}
return getType();
}

Some files were not shown because too many files have changed in this diff Show More