Compare commits

...

191 Commits

Author SHA1 Message Date
Mark Paluch
595fde7b04 DATAMONGO-2648 - Release version 3.1.1 (2020.0.1). 2020-11-11 11:58:58 +01:00
Mark Paluch
01f4e73b48 DATAMONGO-2648 - Prepare 3.1.1 (2020.0.1). 2020-11-11 11:58:35 +01:00
Mark Paluch
2934c4886b DATAMONGO-2648 - Updated changelog. 2020-11-11 11:58:18 +01:00
Christoph Strobl
080c798721 DATAMONGO-2644 - ProjectOperation no longer errors on inclusion of default _id field.
Original pull request: #890.
2020-11-10 09:40:49 +01:00
Christoph Strobl
7cfb68e6be DATAMONGO-2635 - Enforce aggregation pipeline mapping.
Avoid using the Aggregation.DEFAULT_CONTEXT which does not map contained values to the according MongoDB representation. We now use a relaxed aggregation context, preserving given field names, where possible.

Original pull request: #890.
2020-11-10 09:40:49 +01:00
Mark Paluch
1e24abe8e5 DATAMONGO-2639 - Enable maintenance branch build. 2020-10-29 09:43:58 +01:00
Mark Paluch
a316d156dc DATAMONGO-2639 - After release cleanups. 2020-10-28 16:10:54 +01:00
Mark Paluch
6563b125eb DATAMONGO-2639 - Prepare next development iteration. 2020-10-28 16:10:50 +01:00
Mark Paluch
c9251b1b29 DATAMONGO-2639 - Release version 3.1 GA (2020.0.0). 2020-10-28 15:46:54 +01:00
Mark Paluch
373f07e176 DATAMONGO-2639 - Prepare 3.1 GA (2020.0.0). 2020-10-28 15:46:31 +01:00
Mark Paluch
f5e2bdc7ef DATAMONGO-2639 - Updated changelog. 2020-10-28 15:46:17 +01:00
Mark Paluch
30e63fffe2 DATAMONGO-2625 - Updated changelog. 2020-10-28 15:03:01 +01:00
Mark Paluch
83136b4e60 DATAMONGO-2624 - Updated changelog. 2020-10-28 12:15:04 +01:00
Mark Paluch
56697545a3 DATAMONGO-2641 - Updated changelog. 2020-10-28 11:32:27 +01:00
Robin Dupret
76eecc443e DATAMONGO-2638 - Fix list item rendering in reference documentation.
Original Pull Request: #885
2020-10-27 13:31:45 +01:00
LiangYong
1f81806809 DATAMONGO-2638 - Fix aggregation input parameter syntax in reference documentation.
Original Pull Request: #881
2020-10-27 13:31:35 +01:00
Greg L. Turnquist
2d348be5b2 DATAMONGO-2629 - Use JDK 15 for next CI jobs. 2020-10-26 13:26:11 -05:00
Christoph Strobl
bbbe369093 DATAMONGO-2642 - Upgrade MongoDB drivers to 4.1.1. 2020-10-26 12:46:07 +01:00
Christoph Strobl
5aa29fc7b8 DATAMONGO-2626 - After release cleanups. 2020-10-14 14:48:47 +02:00
Christoph Strobl
05fc6546ff DATAMONGO-2626 - Prepare next development iteration. 2020-10-14 14:48:45 +02:00
Christoph Strobl
2c6e645a3d DATAMONGO-2626 - Release version 3.1 RC2 (2020.0.0). 2020-10-14 14:28:55 +02:00
Christoph Strobl
20f702512b DATAMONGO-2626 - Prepare 3.1 RC2 (2020.0.0). 2020-10-14 14:27:37 +02:00
Christoph Strobl
ad77f23364 DATAMONGO-2626 - Updated changelog. 2020-10-14 14:27:30 +02:00
Mark Paluch
9af8a73290 DATAMONGO-2616 - Polishing.
Reformat code. Merge if-statements.

Original pull request: #889.
2020-10-07 11:35:47 +02:00
Christoph Strobl
aaa4557887 DATAMONGO-2616 - Short circuit id value assignment in MongoConverter.
Original pull request: #889.
2020-10-07 11:35:40 +02:00
Mark Paluch
217be64a77 DATAMONGO-2623 - Polishing.
Avoid nullable method arguments and add assertions. Introduce build() method to AccumulatorFinalizeBuilder to build Accumulator without specifying a finalize function.

Original pull request: #887.
2020-10-07 09:51:08 +02:00
Christoph Strobl
0ef852a8fc DATAMONGO-2623 - Add support for $function and $accumulator aggregation operators.
Original pull request: #887.
2020-10-07 09:50:51 +02:00
Mark Paluch
26f0a1c7f9 DATAMONGO-2622 - Polishing.
Rename AggregationPipeline.requiresRelaxedChecking() to containsUnionWith() to avoid the concept of field validation leaking into AggregationPipeline.

Refactor AggregationOperation to consistently check their type and fallback to the operator check to allow for consistent checks when using custo AggregationOperations.

Original pull request: #886.
2020-10-06 12:09:18 +02:00
Christoph Strobl
230c32041a DATAMONGO-2622 - Add support for $unionWith aggregation stage.
We now support the $unionWith aggregation stage via the UnionWithOperation that performs a union of two collections by combining pipeline results, potentially containing duplicates, into a single result set that is handed over to the next stage.
In order to remove duplicates it is possible to append a GroupOperation right after UnionWithOperation.
If the UnionWithOperation uses a pipeline to process documents, field names within the pipeline will be treated as is. In order to map domain type property names to actual field names (considering potential org.springframework.data.mongodb.core.mapping.Field annotations) make sure the enclosing aggregation is a TypedAggregation and provide the target type for the $unionWith stage via mapFieldsTo(Class).

Original pull request: #886.
2020-10-06 12:09:12 +02:00
Mark Paluch
4548d07826 DATAMONGO-2596 - Polishing.
Refactor KPropertyPath.toString() into KProperty.asPath() extension function to allow rendering simple properties and property paths into a String property path.

Original pull request: #880.
2020-10-06 10:18:52 +02:00
Yoann de Martino
b879ec8c0f DATAMONGO-2596 - Introduce extension to render KProperty/KPropertyPath as property path.
Original pull request: #880.
2020-10-06 10:18:19 +02:00
Mark Paluch
c0581c4943 DATAMONGO-2294 - Polishing.
Reorganize imports after Delomboking. Use for-loop instead of Stream.forEach(…). Add Javadoc to methods. Add since tags.

Simplify tests.

Original pull request: #761.
2020-10-05 17:00:58 +02:00
owen-q
85022d24f3 DATAMONGO-2294 - Support query projections with collection types.
Query include/exclude now accepts a vararg array of fields to specify multiple fields at once.

Original pull request: #761.
2020-10-05 17:00:37 +02:00
Christoph Strobl
b2927ab419 DATAMONGO-2633 - Fix json parsing of nested arrays in ParameterBindingDocumentCodec.
Original pull request: #888.
2020-10-05 15:34:50 +02:00
Mark Paluch
91c39e2825 DATAMONGO-2630 - Add support for suspend repository query methods returning List<T>. 2020-09-22 15:01:09 +02:00
Greg L. Turnquist
965a34efd3 DATAMONGO-2629 - Only test other versions for local changes on main branch. 2020-09-18 11:08:38 -05:00
Mark Paluch
046cbb52a1 DATAMONGO-2608 - After release cleanups. 2020-09-16 14:05:28 +02:00
Mark Paluch
edfd07a3d0 DATAMONGO-2608 - Prepare next development iteration. 2020-09-16 14:05:24 +02:00
Mark Paluch
b4befc36c0 DATAMONGO-2608 - Release version 3.1 RC1 (2020.0.0). 2020-09-16 13:57:41 +02:00
Mark Paluch
6034fc1cbd DATAMONGO-2608 - Prepare 3.1 RC1 (2020.0.0). 2020-09-16 13:57:08 +02:00
Mark Paluch
61f4770b4a DATAMONGO-2608 - Updated changelog. 2020-09-16 13:56:57 +02:00
Mark Paluch
c9cfe7acd6 DATAMONGO-2609 - Updated changelog. 2020-09-16 12:16:30 +02:00
Mark Paluch
415ceeef63 DATAMONGO-2593 - Updated changelog. 2020-09-16 11:20:07 +02:00
Mark Paluch
1bdcb88430 DATAMONGO-2592 - Updated changelog. 2020-09-16 10:38:57 +02:00
Christoph Strobl
1a134aa444 DATAMONGO-2618 - Fix visibility of ReplaceRootDocumentOperation. 2020-09-14 13:43:56 +02:00
Mark Paluch
c1da95f5dc DATAMONGO-2621 - Adapt to changed array assertions in AssertJ. 2020-09-09 15:55:48 +02:00
Christoph Strobl
c9c005400c DATAMONGO-2613 - Polishing.
Use the opportunity to remove public modifiers from touched test class.

Original Pull Request: #883
2020-08-20 09:00:21 +02:00
Michal Kurcius
b388659c3f DATAMONGO-2613 - Fix single element ArrayJsonSchemaObject to document mapping.
Now toDocument calls toDocument on items correctly.

Original Pull Request: #883
2020-08-20 08:59:46 +02:00
Mark Paluch
90aa7b8f89 DATAMONGO-2594 - Updated changelog. 2020-08-12 13:25:47 +02:00
Mark Paluch
542de64711 DATAMONGO-2579 - After release cleanups. 2020-08-12 12:00:22 +02:00
Mark Paluch
88b1f9fcb3 DATAMONGO-2579 - Prepare next development iteration. 2020-08-12 12:00:19 +02:00
Mark Paluch
450365992a DATAMONGO-2579 - Release version 3.1 M2 (2020.0.0). 2020-08-12 11:52:05 +02:00
Mark Paluch
fd25f39236 DATAMONGO-2579 - Prepare 3.1 M2 (2020.0.0). 2020-08-12 11:51:40 +02:00
Mark Paluch
a7e3ed2e37 DATAMONGO-2579 - Updated changelog. 2020-08-12 11:51:28 +02:00
Mark Paluch
5795a507bd DATAMONGO-1836 - Polishing.
Revert constructor change of AggregationOptions to not break existing code. Update since tags. Reformat code.

Align visibility of AggregationOptionsTests with JUnit 5 rules. Update documentation.

Original pull request: #878.
2020-08-06 11:25:41 +02:00
Yadhukrishna S Pai
22bd3e64be DATAMONGO-1836 - Add support to hint in aggregation options.
Original pull request: #878.
2020-08-06 11:25:36 +02:00
Mark Paluch
6e47d5c76e DATAMONGO-2603 - Polishing.
Add missing Deprecated annotation.
2020-08-04 13:35:26 +02:00
Mark Paluch
bfab233d2f DATAMONGO-2603 - Adopt to Reactor 3.4 changes.
Align with ContextView and changes in other operators.
2020-08-04 13:35:26 +02:00
Christoph Strobl
c6f12ef0e2 DATAMONGO-2602 - Upgrade MongoDB drivers to 4.1.0 2020-08-03 17:14:24 +02:00
Mark Paluch
707ad8e232 DATAMONGO-1894 - Polishing.
Preinitialize EvaluationContextProvider with ReactiveQueryMethodEvaluationContextProvider to not require setting properties on vanilla ReactiveMongoRepositoryFactory objects.
2020-07-31 11:44:07 +02:00
Mark Paluch
b1f5717d63 DATAMONGO-2601 - Suppress results for suspended query methods returning kotlin.Unit.
We now discard results for suspended query methods if the return type is kotlin.Unit.

Related ticket: DATACMNS-1779
2020-07-31 11:44:07 +02:00
Mark Paluch
95c9789f43 DATAMONGO-2599 - Eagerly consider enum types as simple types.
MongoSimpleTypes now eagerly checks if a type is a simple one to avoid PersistentEntity registration for ChronoUnit.
2020-07-30 16:19:10 +02:00
Mark Paluch
8e84d397e2 DATAMONGO-2564 - Fix link to code of conduct. 2020-07-28 15:40:26 +02:00
Mark Paluch
2ea3ceda2d DATAMONGO-2598 - Polishing.
Original pull request: #872.
2020-07-28 15:21:05 +02:00
Jay Bryant
6a43f28466 DATAMONGO-2598 - Wording changes.
Removed the language of oppression and violence
and replaced it with more neutral language.

Note that problematic words in the code have
to remain in the docs until the code changes.

Original pull request: #872.
2020-07-28 15:20:55 +02:00
Mark Paluch
a44a0034b7 DATAMONGO-2557 - Polishing.
Inline methods.

Original pull request: #879.
2020-07-27 09:02:05 +02:00
Christoph Strobl
0085c8063a DATAMONGO-2557 - Use configured CodecRegistry when parsing String based queries instead of default one.
Original pull request: #879.
2020-07-27 09:01:58 +02:00
Christoph Strobl
873fffa202 DATAMONGO-1894 - Polishing.
Remove superfluous Optional wrappers and unify SpEL dependency resolution.

Original Pull Request: #874
2020-07-22 14:02:12 +02:00
Mark Paluch
41607b10d0 DATAMONGO-1894 - Introduce cached ExpressionParser.
Original Pull Request: #874
2020-07-22 14:01:47 +02:00
Mark Paluch
66fae82798 DATAMONGO-1894 - Use reactive SpEL extensions for SpEL evaluation in query execution.
Original Pull Request: #874
2020-07-22 14:01:20 +02:00
Christoph Strobl
00aaf2145b DATAMONGO-2591 - Upgrade MongoDB drivers to 4.1.0-rc0. 2020-07-22 13:27:51 +02:00
Mark Paluch
430c166a2b DATAMONGO-2568 - Updated changelog. 2020-07-22 10:37:57 +02:00
Mark Paluch
79c647a4d8 DATAMONGO-2567 - Updated changelog. 2020-07-22 10:08:43 +02:00
Mark Paluch
1b5a22730b DATAMONGO-2566 - Updated changelog. 2020-07-22 09:44:28 +02:00
Christoph Strobl
a8a364c2de DATAMONGO-2586 - Polishing.
Add tests to ensure no reactive auditing callback is registered when using imperative configuration and vice versa.
Update wording and minor code style tweaks.

Original Pull Request: #877
2020-07-17 11:09:35 +02:00
Mark Paluch
6bafcea539 DATAMONGO-2586 - Add support for reactive auditing.
We now provide a fully reactive variant for auditing with EnableReactiveMongoAuditing.

Original Pull Request: #877
2020-07-17 10:42:41 +02:00
Mark Paluch
2c1a3cf03e DATAMONGO-2536 - Polishing.
Encapsulate skipResults in AggregationOptions. Reformat code. Add override Javadoc.

Original pull request: #876.
2020-07-16 09:42:42 +02:00
Christoph Strobl
6cb89d7452 DATAMONGO-2536 - Add option to skip reading aggregation result.
Introduce dedicated AggregationPipeline to encapsulate pipeline stages.

Original pull request: #876.
2020-07-16 09:42:26 +02:00
Mark Paluch
2026f8729e DATAMONGO-2571 - Polishing.
Reduce test method visibility for JUnit 5.

Original pull request: #873.
2020-07-15 15:33:38 +02:00
Christoph Strobl
bf89400182 DATAMONGO-2571 - Fix regular expression parameter binding for String-based queries.
Original pull request: #873.
2020-07-15 15:33:30 +02:00
Mark Paluch
6c8cb9eb85 DATAMONGO-2490 - Polishing.
Remove unnecessary code. Reuse session-associated collection when logging to avoid unqualified calls to MongoDbFactory.getMongoDatabase(). Create collection before transaction in test for compatibility with older MongoDB servers.

Original pull request: #875.
2020-07-15 15:13:58 +02:00
Christoph Strobl
966504dfa6 DATAMONGO-2490 - Fix dbref fetching during ongoing transaction.
Original pull request: #875.
2020-07-15 15:13:50 +02:00
Mark Paluch
b266bd6feb DATAMONGO-2544 - After release cleanups. 2020-06-25 11:58:22 +02:00
Mark Paluch
a6a4a0b3b6 DATAMONGO-2544 - Prepare next development iteration. 2020-06-25 11:58:19 +02:00
Mark Paluch
2a66cadaa6 DATAMONGO-2544 - Release version 3.1 M1 (2020.0.0). 2020-06-25 11:48:49 +02:00
Mark Paluch
a70629697b DATAMONGO-2544 - Prepare 3.1 M1 (2020.0.0). 2020-06-25 11:48:19 +02:00
Mark Paluch
d52785533d DATAMONGO-2544 - Updated changelog. 2020-06-25 11:48:10 +02:00
Christoph Strobl
cee1d976de DATAMONGO-2285 - Polishing.
Preserve existing logic translating com.mongodb.MongoBulkWriteException that might be thrown by calling MongoOperations.insertAll(Collection), and move bulk operation translation to DefaultBulkOperations.
Along the lines remove the no longer used PersistenceExceptionTranslator from DefaultBulkOperations.

Original Pull Request: #862
2020-06-23 13:22:03 +02:00
Jacob Botuck
f907dbc559 DATAMONGO-2285 - Throw BulkOperationException instead of translated one when running bulk operations.
Return BulkOperationException unless it is a writeConcernError in which case use existing behavior.

Original Pull Request: #862
2020-06-23 13:21:24 +02:00
Christoph Strobl
613d085bb7 DATAMONGO-1569 - Polishing.
Update Javadoc and avoid unrelated index creation during tests due to class path scanning.

Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Christoph Strobl
94a64a156f DATAMONGO-1569 - Add partialFilter to Indexed annotation.
Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Dave Perryman
41e60e5c25 DATAMONGO-1569 - Add support for partial filter expressions in compound index annotations
Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Christoph Strobl
a254576a6e DATAMONGO-2574 - Polishing.
Fix issue in reactive API and add unit tests.

Original Pull Request: #868
2020-06-22 13:32:03 +02:00
konradend
390b5e7b7e DATAMONGO-2574 - Do not overwrite contentType for GridFsFile.
Original Pull Request: #868
2020-06-22 13:32:03 +02:00
Mark Paluch
66dcb8f662 DATAMONGO-2576 - Upgrade to Hibernate Validator 5.4.3.
Add also javax.el to avoid failures in early expression language initialization.
2020-06-22 13:21:32 +02:00
Christoph Strobl
2eaa2d38af DATAMONGO-2556 - Polishing.
Original pull request: #867.
2020-06-22 13:02:14 +02:00
Christoph Strobl
1290898c2b DATAMONGO-2556 - Add estimatedCount for collections.
The newly introduced methods delegate to the drivers MongoCollection.estimatedDocumentCount.

Original pull request: #867.
2020-06-22 13:02:06 +02:00
Mark Paluch
c4ae269b14 DATAMONGO-2570 - Polishing.
Add assertions. Use method references where possible.

Original pull request: #871.
2020-06-22 10:39:44 +02:00
Mehran Behnam
a4ef46d641 DATAMONGO-2570 - Change type of count variable to primitive.
Avoiding unintentional unboxing.

Original pull request: #871.
2020-06-22 10:39:25 +02:00
Mark Paluch
a27939808b DATAMONGO-2558 - Polishing.
Fixed issue number in tests.

Original pull request: #866.
2020-06-21 20:04:09 +02:00
Mark Paluch
da7fc927fa DATAMONGO-2558 - Add integration test for RxJava 3 repositories.
Update Javadoc and reference documentation.

Original pull request: #866.
2020-06-21 20:03:30 +02:00
Christoph Strobl
f768906684 DATAMONGO-2572 - Remove trailing whitespaces from xsd files.
Original Pull Request: #870
2020-06-17 13:07:00 +02:00
Mark Paluch
61a228f8ac DATAMONGO-2572 - Remove usage of Oppressive Language.
Replaced blacklist with denylist and introduce meta keyword SECONDARY_READS as we no longer use MongoDB API with the initial replication concept.

Original Pull Request: #870
2020-06-17 13:05:45 +02:00
Mark Paluch
837b333d7a DATAMONGO-2543 - Updated changelog. 2020-06-10 14:30:55 +02:00
Mark Paluch
ffd4166b65 DATAMONGO-2533 - Updated changelog. 2020-06-10 12:29:55 +02:00
Mark Paluch
083050fc3c DATAMONGO-2532 - Updated changelog. 2020-06-10 11:48:52 +02:00
Mark Paluch
efbf9c8305 DATAMONGO-2565 - Polishing.
Add unit test to verify behavior. Cleanup code.

Original pull request: #869.
2020-06-10 10:25:25 +02:00
BraveLeeLee
4fdf171f7d DATAMONGO-2565 - Evaluate correct expression when obtaining collation from MongoPersistentEntity.
Original pull request: #869.
2020-06-10 10:25:25 +02:00
Mark Paluch
76990f4915 DATAMONGO-2564 - Use standard Spring code of conduct.
Using https://github.com/spring-projects/.github/blob/master/CODE_OF_CONDUCT.md.
2020-06-09 16:10:27 +02:00
Mark Paluch
4defad57c9 DATAMONGO-2562 - Polishing.
Fix typo in exception message.
2020-06-09 11:18:25 +02:00
Mark Paluch
431f7e6b78 DATAMONGO-2562 - Fix return type detection for suspended Kotlin methods.
See DATACMNS-1738 for further reference.
2020-06-09 11:18:25 +02:00
Mark Paluch
e5157f1c17 DATAMONGO-2560 - Upgrade MongoDB drivers to 4.0.4. 2020-06-08 15:54:53 +02:00
Mark Paluch
af091bf6be DATAMONGO-2542 - Polishing.
Fix nullable annotation.

Original pull request: #863.
2020-05-26 10:32:03 +02:00
Christoph Strobl
84ac0e8a85 DATAMONGO-2542 - Shortcut PersistentPropertyPath resolution during query mapping.
By shortcutting the path resolution we avoid checking keywords like $in against a potential path expression.

Original pull request: #863.
2020-05-26 10:31:57 +02:00
Mark Paluch
2a150adc40 DATAMONGO-2545 - Polishing.
Fix warnings and typos.

Original pull request: #864.
2020-05-26 10:14:18 +02:00
Christoph Strobl
feb3018d19 DATAMONGO-2545 - Fix full Query Document binding resulting from SpEL.
We reenabled annotated queries using a SpEL expression resulting in the actual query document.

Original pull request: #864.
2020-05-26 10:14:14 +02:00
Christoph Strobl
3af7269dbb DATAMONGO-2545 - Fix regression in String query SpEL parameter binding.
We reenabled parameter binding within SpEL using query parameter placeholders ?0, ?1,... instead of their array index [0],[1],...

Original pull request: #864.
2020-05-26 10:14:08 +02:00
Christoph Strobl
af39b422b6 DATAMONGO-2547 - Use target class ClassLoader instead of default CL when creating proxy instances.
Original pull request: #865.
2020-05-26 08:50:01 +02:00
Mark Paluch
8b50778350 DATAMONGO-2553 - Fix reference documentation links.
Remove links to removed documentations sections.
2020-05-19 11:36:37 +02:00
Mark Paluch
ce2f8a7bf5 DATAMONGO-2538 - Polishing.
Reformat code. Convert utility classes to abstract ones.

Original pull request: #861.
2020-05-14 11:02:38 +02:00
Christoph Strobl
26fa0c8285 DATAMONGO-2538 - Delombok source files.
Original pull request: #861.
2020-05-14 11:02:20 +02:00
Mark Paluch
3fda554f81 DATAMONGO-2534 - After release cleanups. 2020-05-12 12:40:30 +02:00
Mark Paluch
c6a86226e0 DATAMONGO-2534 - Prepare next development iteration. 2020-05-12 12:40:28 +02:00
Mark Paluch
f88d1de068 DATAMONGO-2534 - Release version 3.0 GA (Neumann). 2020-05-12 12:28:23 +02:00
Mark Paluch
62bfde2b6b DATAMONGO-2534 - Prepare 3.0 GA (Neumann). 2020-05-12 12:27:59 +02:00
Mark Paluch
93a27f80a3 DATAMONGO-2534 - Updated changelog. 2020-05-12 12:27:47 +02:00
Christoph Strobl
c2b0090ff1 DATAMONGO-2541 - Upgrade to MongoDB 4.0.3 Drivers. 2020-05-11 17:00:39 +02:00
Florian Bernard
0345abb5f8 DATAMONGO-2509 - Add missing Query constructor in reference documentation.
Original pull request: #846.
2020-05-06 11:52:16 +02:00
Mark Paluch
35196e3129 DATAMONGO-2509 - Polishing.
Fix typos, improve wording. Reworks documentation specific to MongoDB 3 and 4.

Original pull request: #853.
2020-05-06 11:46:29 +02:00
Christoph Strobl
37d99c4948 DATAMONGO-2509 - Update Javadoc.
Original pull request: #853.
2020-05-06 11:21:11 +02:00
Christoph Strobl
288e04b2d3 DATAMONGO-2509 - Update Reference Documentation.
Related to: DATAMONGO-365, DATAMONGO-384, DATAMONGO-2192, DATAMONGO-2407

Original pull request: #853.
2020-05-06 11:21:02 +02:00
Greg Turnquist
689c1480bd DATAMONGO-2535 - Remove Travis CI. 2020-05-04 15:09:00 -05:00
Mark Paluch
09fbe6060e DATAMONGO-2503 - After release cleanups. 2020-04-28 15:11:43 +02:00
Mark Paluch
d5cf3dfc22 DATAMONGO-2503 - Prepare next development iteration. 2020-04-28 15:11:42 +02:00
Mark Paluch
0f987f44ef DATAMONGO-2503 - Release version 3.0 RC2 (Neumann). 2020-04-28 15:03:53 +02:00
Mark Paluch
5df22233d8 DATAMONGO-2503 - Prepare 3.0 RC2 (Neumann). 2020-04-28 15:03:33 +02:00
Mark Paluch
9751c6bc8b DATAMONGO-2503 - Updated changelog. 2020-04-28 15:03:26 +02:00
Mark Paluch
7dc509953a DATAMONGO-2500 - Updated changelog. 2020-04-28 14:46:50 +02:00
Mark Paluch
2f4f1e524d DATAMONGO-2484 - Updated changelog. 2020-04-28 11:59:01 +02:00
Christoph Strobl
26ddf9d59f DATAMONGO-2531 - Fix MongoClientSettings UUID configuration hook in MongoConfigurationSupport.
Client code overriding configureClientSettings does not automatically remove the default UUidRepresentation settings.
2020-04-27 09:30:37 +02:00
Mark Paluch
96ff4e1d14 DATAMONGO-2461 - Polishing.
Remove superfluous Test annotation as RepeatFailedTest acts as a TestTemplate so adding the Test annotation causes the test to run twice.
2020-04-24 09:03:18 +02:00
Mark Paluch
2af13c27a7 DATAMONGO-2529 - Ensure that MappingMongoConverter.read(…) is never called with null.
Previously, various methods attempted to pass a null argument as source for the converter. The API is non-null and implementations relying on these constraints were easily breakable.

We now make sure that the source is never null.
2020-04-23 14:57:52 +02:00
Mark Paluch
f4d2fc6231 DATAMONGO-2504 - Polishing.
Update equals/hashCode implementation to use the Spring Data form. Make fields final where possible. Use diamond syntax. Reorder methods. Reformat code. Extend tests.

Original pull request: #848.
2020-04-23 12:24:26 +02:00
ddebray
3ab679bcc7 DATAMONGO-2504 - Add hashCode and equals to TextCriteria and Term.
Original pull request: #848.
2020-04-23 12:24:10 +02:00
Mark Paluch
318d552797 DATAMONGO-2505 - Polishing.
Simplify operators. Remove Lombok usage from newly introduced code. Update reference documentation. Reformat code.

Original pull request: #854.
2020-04-23 12:02:46 +02:00
Mathieu Ouellet
8cfbd39c7e DATAMONGO-2505 - Deferred Database retrieval from ReactiveMongoDatabaseFactory.
Change ReactiveMongoDatabaseFactory#getMongoDatabase() methods return Mono to enable access to the subscriber context.

Original pull request: #854.
2020-04-23 12:02:15 +02:00
Christoph Strobl
3a14af5485 DATAMONGO-2513 - Fix Eq aggregation operator comparing collection values.
Original pull request: #855.
2020-04-22 11:46:49 +02:00
Mark Paluch
00034d899a DATAMONGO-2516 - Polishing.
Reflect nullability change in TextScore Javadoc. Update documentation.

Original pull request: #856.
2020-04-22 11:12:50 +02:00
Christoph Strobl
fba6d7d8be DATAMONGO-2516 - Assert compatibility with MongoDB 4.4-rc0.
Fixes:
- Fields list must not contain text search score property when no $text criteria present.
- Sort must not be an empty document when running map reduce.
- Timeout in tests creating indexes.

Changes:
- score property might now be null when not having a $text criteria present. Was zero before.

Original pull request: #856.
2020-04-22 11:12:29 +02:00
Mark Paluch
95c4707902 DATAMONGO-2523 - Polishing.
Reformat code.

Original pull request: #859.
2020-04-22 10:14:50 +02:00
Christoph Strobl
32f3e60c9f DATAMONGO-2523 - Fix Json binding of SpEL expressions in arrays.
The closing bracket must not have a leading whitespace.

Original pull request: #859.
2020-04-22 10:08:57 +02:00
Mark Paluch
b57e571033 DATAMONGO-2517 - Polishing.
Reformat code.

Original pull request: #857.
2020-04-21 16:02:09 +02:00
Christoph Strobl
6604c507dd DATAMONGO-2517 - Fix invalid entity creation for text queries.
Fix a glitch in the MappingMongoConverter that uses the single String argument constructor (since it matches in type and parameter count to the given input string) to falsely instantiate an Entity when it should not.

Original pull request: #857.
2020-04-21 16:02:04 +02:00
Christoph Strobl
e1df28797a DATAMONGO-2507 - Polishing.
Add 'matching' default method also to imperative variant (ExecutableFindOperation), fix & add tests using 'distinct'.
Update Javadoc and rename input arg 'criteriaDefinition' to 'criteria'.

Original Pull Request: #852
2020-04-14 10:22:01 +02:00
Juergen Zimmermann
c6630aa279 DATAMONGO-2507 - Add default method matching(CriteriaDefinition) to ReactiveFindOperation.DistinctWithQuery.
Original Pull Request: #852
2020-04-14 09:51:23 +02:00
Greg Turnquist
bf921cdbd7 DATAMONGO-2510 - Use JDK 14 for Java.NEXT CI testing. 2020-04-09 14:29:16 -05:00
Christoph Strobl
a1b4e6df59 DATAMONGO-2508 - Upgrade to MongoDB 4.0.2 Drivers. 2020-04-08 11:38:19 +02:00
Christoph Strobl
4b3312998a DATAMONGO-2506 - Provide meaningful error message when using unsupported return type in repository aggregation method.
We improved the error message for unsupported return types instead of running into an IllegalArgumentException for unique results.

Original pull request: #851.
2020-04-07 14:58:38 +02:00
Mark Paluch
c5501db577 DATAMONGO-2502 - Polishing.
Extend tests. Fix generics. Consistently use compiled patterns for positional placeholder removal.

Original pull request: #847.
2020-04-07 14:10:20 +02:00
Christoph Strobl
936a0d35f7 DATAMONGO-2502 - Fix nested array path mapping for updates.
Original pull request: #847.
2020-04-07 14:10:09 +02:00
Christoph Strobl
5dd91d0b6d DATAMONGO-1677 - Polishing.
Switch tests to JUnit Jupiter.

Original Pull Request: #849
2020-04-06 08:51:30 +02:00
Jens Schauder
28510de6c8 DATAMONGO-1677 - Adds a test to confirm a query with more than 10 arguments works just fine.
Original Pull Request: #849
2020-04-06 08:50:56 +02:00
Mark Paluch
4bbf4cd5cf DATAMONGO-2492 - After release cleanups. 2020-03-31 15:08:05 +02:00
Mark Paluch
90bd3f0f18 DATAMONGO-2492 - Prepare next development iteration. 2020-03-31 15:08:04 +02:00
Mark Paluch
1e35116419 DATAMONGO-2492 - Release version 3.0 RC1 (Neumann). 2020-03-31 14:59:41 +02:00
Mark Paluch
dd336f0ecb DATAMONGO-2492 - Prepare 3.0 RC1 (Neumann). 2020-03-31 14:59:20 +02:00
Mark Paluch
d020219ded DATAMONGO-2492 - Updated changelog. 2020-03-31 14:59:15 +02:00
Mark Paluch
0345eff69a DATAMONGO-2477 - Polishing.
Make sure that indexes get created where needed.
2020-03-30 14:37:42 +02:00
Mark Paluch
55fee27fb6 DATAMONGO-625 - Polishing.
Introduce default interface methods where possible. Rename save(…) to store(…) to align with method naming. Reduce constructor visibility to avoid invalid API usage. Replace mutable object in builder with fields to avoid mutation of already built objects when reusing the builder.
Remove Options.chunked(…) factory method to avoid confusion with chunkSize method.

Reformat code, strip trailing whitespaces.

Original pull request: #842.
2020-03-30 14:19:45 +02:00
Christoph Strobl
ffba352e15 DATAMONGO-625 - Add support for GridFS with predefined id.
We now support storing GridFS content with predefined id, which allows to replace an existing resource instead of having to delete and reupload it.

Original pull request: #842.
2020-03-30 14:19:26 +02:00
Mark Paluch
1118df5550 DATAMONGO-2477 - Polishing.
Remove warn log for auto-index creation. Remove unused fields. Document index creation in reference documentation.

Original pull request: #845.
2020-03-26 15:14:03 +01:00
Christoph Strobl
29f05af733 DATAMONGO-2477 - Disable auto index creation by default.
Original pull request: #845.
2020-03-26 15:14:03 +01:00
Oliver Drotbohm
7bac739146 DATAMONGO-2501 - Upgrade to Querydsl 4.3.
Adapted to changes in the APT APIs.
2020-03-26 14:38:51 +01:00
Mark Paluch
6366d3cec1 DATAMONGO-2485 - Updated changelog. 2020-03-25 10:59:47 +01:00
Christoph Strobl
44913abd80 DATAMONGO-2300 - Polishing.
Move null check to event publishing logic.

Original Pull Request: #763
2020-03-23 09:29:49 +01:00
Heesu Jung
7a7f7c942d DATAMONGO-2300 - Add check rawType is null in readMap.
Original Pull Request: #763
2020-03-23 09:29:19 +01:00
Christoph Strobl
e9c9938016 DATAMONGO-2498 - Upgrade to MongoDB 4.0.1 Drivers. 2020-03-23 09:18:07 +01:00
Mark Paluch
c9da0a75ff DATAMONGO-931 - Polishing.
Reformat code. Add private constructor to prevent unwanted instantiation.

Original pull request: #844.
2020-03-20 14:45:11 +01:00
Christoph Strobl
581961e79a DATAMONGO-931 - Add support for $redact aggregation.
We now support $redact via Aggregation.redact.

Aggregation.redact(ConditionalOperators.when(Criteria.where("level").is(5))
    .then(RedactOperation.PRUNE)
    .otherwise(RedactOperation.DESCEND));

Original pull request: #844.
2020-03-20 14:40:16 +01:00
Christoph Strobl
0e0d726457 DATAMONGO-2475 - Polishing.
Fix reduction of $and/$or operations with more than two arguments.

Original Pull Request: #834
2020-03-20 10:15:10 +01:00
Enrique León Molina
7b5fea960f DATAMONGO-2475 - MongodbDocumentSerializer: reduce nested ANDs and ORs.
Reduce the number of nested $and / $or clauses by combining them into a single document where possible. This allows to simplify the following statement

{
  "$or": [
    {
      "$or": [
        {
          "$or": [
            {
              "$or": [
                { "firstname": "Hencxjo" },
                { "lastname": "Leon" }
              ]
            },
            { "age": { "$lte": 30 } }
          ]
        },
        { "age": { "$gte": 20 } }
      ]
    },
    { "uniqueId": { "$exists": false } }
  ]
}

to just

{
 "$or": [
   { "firstname": "Hencxjo" },
   { "lastname": "Leon" },
   { "age": { "$lte": 30 } },
   { "age": { "$gte": 20 } },
   { "uniqueId": { "$exists": false } }
 ]
}

Original Pull Request: #834
2020-03-20 10:13:37 +01:00
Mark Paluch
a04821ff90 DATAMONGO-2497 - Update documentation regarding @Transient properties usage in the persistence constructor. 2020-03-19 15:37:30 +01:00
Mark Paluch
a6bd41bcf2 DATAMONGO-2416 - Polishing.
Reduce visibility of JUnit 5 test classes/methods.

Original Pull Request: #840
2020-03-17 11:41:39 +01:00
Mark Paluch
6387eb9762 DATAMONGO-2416 - Add convenience methods accepting CriteriaDefinition on Fluent API.
The fluent API now exposes default interface methods accepting CriteriaDefinition for a more concise expression of queries that do not require a Query object.

template.query(Person.class).matching(where("firstname").is("luke")).all()

instead of

template.query(Person.class).matching(query(where("firstname").is("luke"))).all()

Original Pull Request: #840
2020-03-17 11:41:14 +01:00
Mark Paluch
5fb4b036bb DATAMONGO-1026 - Include documentation about custom conversions.
We now include the documentations partial about custom conversions that explains default converter registrations, overrides and system setting timezone-sensitivity.
2020-03-17 10:57:15 +01:00
Mark Paluch
4f0dc04a81 DATAMONGO-2479 - Polishing.
Tweak Javadoc. Update reference documentation. Slightly refactor reactive flows to reduce operator count.

Simplify test fixtures and remove Google Guava usage. Reformat code.

Original pull request: #839.
2020-03-16 11:34:27 +01:00
Roman Puchkovskiy
ee59c6b774 DATAMONGO-2479 - Add AfterConvertCallback and AfterSaveCallback (and their reactive versions).
Previously, only BeforeConvertCallback and BeforeSaveCallback were supported (and their reactive counterparts). This commit adds support for 'after-convert' and 'after-save' events using entity callbacks feature.

Original pull request: #839.
2020-03-16 11:34:13 +01:00
Mark Paluch
b0b905ddb7 DATAMONGO-2488 - Polishing.
Simplify conditional entity check. Reduce test method visibility for JUnit 5.

Original pull request: #841.
2020-03-11 14:51:03 +01:00
Christoph Strobl
7f7be5e47d DATAMONGO-2488 - Fix nested array path field name mapping.
Original pull request: #841.
2020-03-11 14:37:36 +01:00
Jens Schauder
5a49aa6519 DATAMONGO-2473 - After release cleanups. 2020-03-11 09:57:42 +01:00
Jens Schauder
b68079c421 DATAMONGO-2473 - Prepare next development iteration. 2020-03-11 09:57:41 +01:00
382 changed files with 12078 additions and 4431 deletions

View File

@@ -1,40 +0,0 @@
language: java
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
jdk:
- openjdk13
- openjdk-ea
matrix:
allow_failures:
- jdk: openjdk-ea
env:
matrix:
- MONGO_VERSION=4.2.0
- MONGO_VERSION=4.0.14
- MONGO_VERSION=3.6.16
global:
- PROFILE=ci
sudo: false
cache:
directories:
- $HOME/.m2
- downloads
install: true
script:
- "./mvnw clean dependency:list test -Pjava11 -Dsort -U"

View File

@@ -1,27 +0,0 @@
= Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses,
without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at spring-code-of-conduct@pivotal.io.
All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances.
Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident.
This Code of Conduct is adapted from the https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/].

22
Jenkinsfile vendored
View File

@@ -3,7 +3,7 @@ pipeline {
triggers {
pollSCM 'H/10 * * * *'
upstream(upstreamProjects: "spring-data-commons/master", threshold: hudson.model.Result.SUCCESS)
upstream(upstreamProjects: "spring-data-commons/2.4.x", threshold: hudson.model.Result.SUCCESS)
}
options {
@@ -46,16 +46,16 @@ pipeline {
}
}
}
stage('Publish JDK 13 + MongoDB 4.2') {
stage('Publish JDK 15 + MongoDB 4.2') {
when {
changeset "ci/openjdk13-mongodb-4.2/**"
changeset "ci/openjdk15-mongodb-4.2/**"
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-openjdk13-with-mongodb-4.2.0", "ci/openjdk13-mongodb-4.2/")
def image = docker.build("springci/spring-data-openjdk15-with-mongodb-4.2.0", "ci/openjdk15-mongodb-4.2/")
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
image.push()
}
@@ -68,7 +68,7 @@ pipeline {
stage("test: baseline (jdk8)") {
when {
anyOf {
branch 'master'
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -93,8 +93,8 @@ pipeline {
stage("Test other configurations") {
when {
anyOf {
branch 'master'
allOf {
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -139,10 +139,10 @@ pipeline {
}
}
stage("test: baseline (jdk13)") {
stage("test: baseline (jdk15)") {
agent {
docker {
image 'springci/spring-data-openjdk13-with-mongodb-4.2.0:latest'
image 'springci/spring-data-openjdk15-with-mongodb-4.2.0:latest'
label 'data'
args '-v $HOME:/tmp/jenkins-home'
}
@@ -164,7 +164,7 @@ pipeline {
stage('Release to artifactory') {
when {
anyOf {
branch 'master'
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -196,7 +196,7 @@ pipeline {
stage('Publish documentation') {
when {
branch 'master'
branch '3.1.x'
}
agent {
docker {

View File

@@ -10,7 +10,7 @@ Key functional areas of Spring Data MongoDB are a POJO centric model for interac
== Code of Conduct
This project is governed by the link:CODE_OF_CONDUCT.adoc[Spring Code of Conduct]. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
This project is governed by the https://github.com/spring-projects/.github/blob/e3cc2ff230d8f1dca06535aa6b5a4a23815861d4/CODE_OF_CONDUCT.md[Spring Code of Conduct]. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
== Getting Started
@@ -52,11 +52,6 @@ public class MyService {
@EnableMongoRepositories
class ApplicationConfig extends AbstractMongoClientConfiguration {
@Override
public MongoClient mongoClient() {
return MongoClients.create();
}
@Override
protected String getDatabaseName() {
return "springdata";

View File

@@ -1,4 +1,4 @@
FROM adoptopenjdk/openjdk13:latest
FROM adoptopenjdk/openjdk15:latest
ENV TZ=Etc/UTC
ENV DEBIAN_FRONTEND=noninteractive

12
pom.xml
View File

@@ -5,7 +5,7 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.0.0.M4</version>
<version>3.1.1</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.3.0.M4</version>
<version>2.4.1</version>
</parent>
<modules>
@@ -26,8 +26,8 @@
<properties>
<project.type>multi</project.type>
<dist.id>spring-data-mongodb</dist.id>
<springdata.commons>2.3.0.M4</springdata.commons>
<mongo>4.0.0</mongo>
<springdata.commons>2.4.1</springdata.commons>
<mongo>4.1.1</mongo>
<mongo.reactivestreams>${mongo}</mongo.reactivestreams>
<jmh.version>1.19</jmh.version>
</properties>
@@ -134,8 +134,8 @@
<repositories>
<repository>
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
<id>spring-libs-release</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>sonatype-libs-snapshot</id>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.0.0.M4</version>
<version>3.1.1</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>3.0.0.M4</version>
<version>3.1.1</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>3.0.0.M4</version>
<version>3.1.1</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -136,6 +136,13 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava3</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava3}</version>
<optional>true</optional>
</dependency>
<!-- CDI -->
<!-- Dependency order required to build against CDI 1.0 and test with CDI 2.0 -->
<dependency>
@@ -192,7 +199,14 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
<version>5.4.3.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
<scope>test</scope>
</dependency>

View File

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

View File

@@ -45,7 +45,7 @@ public interface MongoDatabaseFactory extends CodecRegistryProvider, MongoSessio
/**
* Obtain a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName
* @param dbName must not be {@literal null}.
* @return never {@literal null}.
* @throws DataAccessException
*/

View File

@@ -79,7 +79,7 @@ public class MongoDatabaseUtils {
* @param factory the {@link MongoDatabaseFactory} to get the {@link MongoDatabase} from.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(String dbName, MongoDatabaseFactory factory) {
public static MongoDatabase getDatabase(@Nullable String dbName, MongoDatabaseFactory factory) {
return doGetMongoDatabase(dbName, factory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
}
@@ -94,7 +94,7 @@ public class MongoDatabaseUtils {
* @param sessionSynchronization the synchronization to use. Must not be {@literal null}.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(String dbName, MongoDatabaseFactory factory,
public static MongoDatabase getDatabase(@Nullable String dbName, MongoDatabaseFactory factory,
SessionSynchronization sessionSynchronization) {
return doGetMongoDatabase(dbName, factory, sessionSynchronization);
}

View File

@@ -33,7 +33,7 @@ public interface MongoDbFactory extends MongoDatabaseFactory {
/**
* Creates a default {@link MongoDatabase} instance.
*
* @return
* @return never {@literal null}.
* @throws DataAccessException
* @deprecated since 3.0. Use {@link #getMongoDatabase()} instead.
*/
@@ -46,7 +46,7 @@ public interface MongoDbFactory extends MongoDatabaseFactory {
* Obtain a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return
* @return never {@literal null}.
* @throws DataAccessException
* @deprecated since 3.0. Use {@link #getMongoDatabase(String)} instead.
*/

View File

@@ -31,6 +31,7 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.0
*/
public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
@@ -38,19 +39,19 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
/**
* Creates a default {@link MongoDatabase} instance.
*
* @return
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase() throws DataAccessException;
Mono<MongoDatabase> getMongoDatabase() throws DataAccessException;
/**
* Obtain a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase(String dbName) throws DataAccessException;
Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException;
/**
* Exposes a shared {@link MongoExceptionTranslator}.
@@ -64,10 +65,7 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
*
* @return never {@literal null}.
*/
@Override
default CodecRegistry getCodecRegistry() {
return getMongoDatabase().getCodecRegistry();
}
CodecRegistry getCodecRegistry();
/**
* Obtain a {@link Mono} emitting a {@link ClientSession} for given {@link ClientSessionOptions options}.

View File

@@ -41,6 +41,7 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.2
*/
public class ReactiveMongoDatabaseUtils {
@@ -142,14 +143,13 @@ public class ReactiveMongoDatabaseUtils {
.flatMap(synchronizationManager -> {
return doGetSession(synchronizationManager, factory, sessionSynchronization) //
.map(it -> getMongoDatabaseOrDefault(dbName, factory.withSession(it)));
})
.onErrorResume(NoTransactionException.class,
e -> Mono.fromSupplier(() -> getMongoDatabaseOrDefault(dbName, factory)))
.defaultIfEmpty(getMongoDatabaseOrDefault(dbName, factory));
.flatMap(it -> getMongoDatabaseOrDefault(dbName, factory.withSession(it)));
}) //
.onErrorResume(NoTransactionException.class, e -> getMongoDatabaseOrDefault(dbName, factory))
.switchIfEmpty(getMongoDatabaseOrDefault(dbName, factory));
}
private static MongoDatabase getMongoDatabaseOrDefault(@Nullable String dbName,
private static Mono<MongoDatabase> getMongoDatabaseOrDefault(@Nullable String dbName,
ReactiveMongoDatabaseFactory factory) {
return StringUtils.hasText(dbName) ? factory.getMongoDatabase(dbName) : factory.getMongoDatabase();
}

View File

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

View File

@@ -0,0 +1,70 @@
/*
* Copyright 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.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.ReactiveAuditorAware;
/**
* Annotation to enable auditing in MongoDB using reactive infrastructure via annotation configuration.
*
* @author Mark Paluch
* @since 3.1
*/
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ReactiveMongoAuditingRegistrar.class)
public @interface EnableReactiveMongoAuditing {
/**
* Configures the {@link ReactiveAuditorAware} bean to be used to lookup the current principal.
*
* @return empty {@link String} by default.
*/
String auditorAwareRef() default "";
/**
* Configures whether the creation and modification dates are set. Defaults to {@literal true}.
*
* @return {@literal true} by default.
*/
boolean setDates() default true;
/**
* Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
*
* @return {@literal true} by default.
*/
boolean modifyOnCreate() default true;
/**
* Configures a {@link DateTimeProvider} bean name that allows customizing the timestamp to be used for setting
* creation and modification dates.
*
* @return empty {@link String} by default.
*/
String dateTimeProviderRef() default "";
}

View File

@@ -96,6 +96,9 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE);
id = StringUtils.hasText(id) ? id : DEFAULT_CONVERTER_BEAN_NAME;
String autoIndexCreation = element.getAttribute("auto-index-creation");
boolean autoIndexCreationEnabled = StringUtils.hasText(autoIndexCreation) && Boolean.valueOf(autoIndexCreation);
parserContext.pushContainingComponent(new CompositeComponentDefinition("Mapping Mongo Converter", element));
BeanDefinition conversionsDefinition = getCustomConversions(element, parserContext);
@@ -199,6 +202,11 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
public static String potentiallyCreateMappingContext(Element element, ParserContext parserContext,
@Nullable BeanDefinition conversionsDefinition, @Nullable String converterId) {
return potentiallyCreateMappingContext(element, parserContext, conversionsDefinition, converterId, false);
}
public static String potentiallyCreateMappingContext(Element element, ParserContext parserContext,
@Nullable BeanDefinition conversionsDefinition, @Nullable String converterId, boolean autoIndexCreation) {
String ctxRef = element.getAttribute("mapping-context-ref");
@@ -226,6 +234,8 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
mappingContextBuilder.addPropertyValue("simpleTypeHolder", simpleTypesDefinition);
}
mappingContextBuilder.addPropertyValue("autoIndexCreation", autoIndexCreation);
parseFieldNamingStrategy(element, parserContext.getReaderContext(), mappingContextBuilder);
ctxRef = converterId == null || DEFAULT_CONVERTER_BEAN_NAME.equals(converterId) ? MAPPING_CONTEXT_BEAN_NAME

View File

@@ -17,7 +17,6 @@ package org.springframework.data.mongodb.config;
import java.lang.annotation.Annotation;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
@@ -28,14 +27,8 @@ import org.springframework.data.auditing.IsNewAwareAuditingHandler;
import org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport;
import org.springframework.data.auditing.config.AuditingConfiguration;
import org.springframework.data.config.ParsingUtils;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.event.AuditingEntityCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* {@link ImportBeanDefinitionRegistrar} to enable {@link EnableMongoAuditing} annotation.
@@ -46,9 +39,6 @@ import org.springframework.util.ClassUtils;
*/
class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
private static boolean PROJECT_REACTOR_AVAILABLE = ClassUtils.isPresent("reactor.core.publisher.Mono",
MongoAuditingRegistrar.class.getClassLoader());
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAnnotation()
@@ -91,7 +81,7 @@ class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(IsNewAwareAuditingHandler.class);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(MongoMappingContextLookup.class);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(PersistentEntitiesFactoryBean.class);
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
builder.addConstructorArgValue(definition.getBeanDefinition());
@@ -116,68 +106,6 @@ class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
registerInfrastructureBeanWithId(listenerBeanDefinitionBuilder.getBeanDefinition(),
AuditingEntityCallback.class.getName(), registry);
if (PROJECT_REACTOR_AVAILABLE) {
registerReactiveAuditingEntityCallback(registry, auditingHandlerDefinition.getSource());
}
}
private void registerReactiveAuditingEntityCallback(BeanDefinitionRegistry registry, Object source) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ReactiveAuditingEntityCallback.class);
builder.addConstructorArgValue(ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), registry));
builder.getRawBeanDefinition().setSource(source);
registerInfrastructureBeanWithId(builder.getBeanDefinition(), ReactiveAuditingEntityCallback.class.getName(),
registry);
}
/**
* Simple helper to be able to wire the {@link MappingContext} from a {@link MappingMongoConverter} bean available in
* the application context.
*
* @author Oliver Gierke
*/
static class MongoMappingContextLookup
implements FactoryBean<MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty>> {
private final MappingMongoConverter converter;
/**
* Creates a new {@link MongoMappingContextLookup} for the given {@link MappingMongoConverter}.
*
* @param converter must not be {@literal null}.
*/
public MongoMappingContextLookup(MappingMongoConverter converter) {
this.converter = converter;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
@Override
public MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> getObject() throws Exception {
return converter.getMappingContext();
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class<?> getObjectType() {
return MappingContext.class;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
@Override
public boolean isSingleton() {
return true;
}
}
}

View File

@@ -95,7 +95,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 org.springframework.data.mongodb.core.convert.MappingMongoConverter} and {@link #mongoMappingContext()}.
* {@link org.springframework.data.mongodb.core.convert.MappingMongoConverter} and {@link MongoMappingContext}.
* Returns an empty {@link MongoCustomConversions} instance by default.
* <p>
* <strong>NOTE:</strong> Use {@link #configureConverters(MongoConverterConfigurationAdapter)} to configure MongoDB
@@ -199,12 +199,12 @@ public abstract class MongoConfigurationSupport {
* Configure whether to automatically create indices for domain types by deriving the
* {@link org.springframework.data.mongodb.core.index.IndexDefinition} from the entity or not.
*
* @return {@literal true} by default. <br />
* <strong>INFO</strong>: As of 3.x the default will be set to {@literal false}.
* @return {@literal false} by default. <br />
* <strong>INFO</strong>: As of 3.x the default is set to {@literal false}; In 2.x it was {@literal true}.
* @since 2.2
*/
protected boolean autoIndexCreation() {
return true;
return false;
}
/**
@@ -217,6 +217,7 @@ public abstract class MongoConfigurationSupport {
protected MongoClientSettings mongoClientSettings() {
MongoClientSettings.Builder builder = MongoClientSettings.builder();
builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
configureClientSettings(builder);
return builder.build();
}
@@ -228,6 +229,6 @@ public abstract class MongoConfigurationSupport {
* @since 3.0
*/
protected void configureClientSettings(MongoClientSettings.Builder builder) {
builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
// customization hook
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 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.config;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
/**
* Simple helper to be able to wire the {@link PersistentEntities} from a {@link MappingMongoConverter} bean available
* in the application context.
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
* @since 3.1
*/
class PersistentEntitiesFactoryBean implements FactoryBean<PersistentEntities> {
private final MappingMongoConverter converter;
/**
* Creates a new {@link PersistentEntitiesFactoryBean} for the given {@link MappingMongoConverter}.
*
* @param converter must not be {@literal null}.
*/
public PersistentEntitiesFactoryBean(MappingMongoConverter converter) {
this.converter = converter;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
@Override
public PersistentEntities getObject() {
return PersistentEntities.of(converter.getMappingContext());
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class<?> getObjectType() {
return PersistentEntities.class;
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright 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.config;
import java.lang.annotation.Annotation;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.data.auditing.ReactiveIsNewAwareAuditingHandler;
import org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport;
import org.springframework.data.auditing.config.AuditingConfiguration;
import org.springframework.data.config.ParsingUtils;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
import org.springframework.util.Assert;
/**
* {@link ImportBeanDefinitionRegistrar} to enable {@link EnableReactiveMongoAuditing} annotation.
*
* @author Mark Paluch
* @since 3.1
*/
class ReactiveMongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAnnotation()
*/
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableReactiveMongoAuditing.class;
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditingHandlerBeanName()
*/
@Override
protected String getAuditingHandlerBeanName() {
return "reactiveMongoAuditingHandler";
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditHandlerBeanDefinitionBuilder(org.springframework.data.auditing.config.AuditingConfiguration)
*/
@Override
protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder(AuditingConfiguration configuration) {
Assert.notNull(configuration, "AuditingConfiguration must not be null!");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ReactiveIsNewAwareAuditingHandler.class);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(PersistentEntitiesFactoryBean.class);
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
builder.addConstructorArgValue(definition.getBeanDefinition());
return configureDefaultAuditHandlerAttributes(configuration, builder);
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#registerAuditListener(org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.support.BeanDefinitionRegistry)
*/
@Override
protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition,
BeanDefinitionRegistry registry) {
Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null!");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ReactiveAuditingEntityCallback.class);
builder.addConstructorArgValue(ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), registry));
builder.getRawBeanDefinition().setSource(auditingHandlerDefinition.getSource());
registerInfrastructureBeanWithId(builder.getBeanDefinition(), ReactiveAuditingEntityCallback.class.getName(),
registry);
}
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AllArgsConstructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -30,6 +28,7 @@ import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.CountOperation;
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.QueryMapper;
@@ -49,12 +48,18 @@ import org.springframework.util.ObjectUtils;
* @author Mark Paluch
* @since 2.1
*/
@AllArgsConstructor
class AggregationUtil {
QueryMapper queryMapper;
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
AggregationUtil(QueryMapper queryMapper,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
this.queryMapper = queryMapper;
this.mappingContext = mappingContext;
}
/**
* Prepare the {@link AggregationOperationContext} for a given aggregation by either returning the context itself it
* is not {@literal null}, create a {@link TypeBasedAggregationOperationContext} if the aggregation contains type
@@ -71,12 +76,17 @@ class AggregationUtil {
return context;
}
if (aggregation instanceof TypedAggregation) {
return new TypeBasedAggregationOperationContext(((TypedAggregation) aggregation).getInputType(), mappingContext,
queryMapper);
if (!(aggregation instanceof TypedAggregation)) {
return new RelaxedTypeBasedAggregationOperationContext(Object.class, mappingContext, queryMapper);
}
return Aggregation.DEFAULT_CONTEXT;
Class<?> inputType = ((TypedAggregation) aggregation).getInputType();
if (aggregation.getPipeline().containsUnionWith()) {
return new RelaxedTypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
/**
@@ -88,7 +98,7 @@ class AggregationUtil {
*/
List<Document> createPipeline(Aggregation aggregation, AggregationOperationContext context) {
if (!ObjectUtils.nullSafeEquals(context, Aggregation.DEFAULT_CONTEXT)) {
if (ObjectUtils.nullSafeEquals(context, Aggregation.DEFAULT_CONTEXT)) {
return aggregation.toPipeline(context);
}

View File

@@ -94,7 +94,6 @@ 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);
@@ -105,7 +104,6 @@ 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);
@@ -115,7 +113,6 @@ 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

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.EqualsAndHashCode;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
@@ -27,6 +25,7 @@ import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.OperationType;
@@ -39,7 +38,6 @@ import com.mongodb.client.model.changestream.OperationType;
* @author Mark Paluch
* @since 2.1
*/
@EqualsAndHashCode
public class ChangeStreamEvent<T> {
@SuppressWarnings("rawtypes") //
@@ -187,8 +185,8 @@ public class ChangeStreamEvent<T> {
return CONVERTED_UPDATER.compareAndSet(this, null, result) ? result : CONVERTED_UPDATER.get(this);
}
throw new IllegalArgumentException(String.format("No converter found capable of converting %s to %s",
fullDocument.getClass(), targetType));
throw new IllegalArgumentException(
String.format("No converter found capable of converting %s to %s", fullDocument.getClass(), targetType));
}
/*
@@ -199,4 +197,27 @@ public class ChangeStreamEvent<T> {
public String toString() {
return "ChangeStreamEvent {" + "raw=" + raw + ", targetType=" + targetType + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ChangeStreamEvent<?> that = (ChangeStreamEvent<?>) o;
if (!ObjectUtils.nullSafeEquals(this.raw, that.raw)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.targetType, that.targetType);
}
@Override
public int hashCode() {
int result = raw != null ? raw.hashCode() : 0;
result = 31 * result + ObjectUtils.nullSafeHashCode(targetType);
return result;
}
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.EqualsAndHashCode;
import java.time.Instant;
import java.util.Arrays;
import java.util.Optional;
@@ -25,7 +23,6 @@ import org.bson.BsonDocument;
import org.bson.BsonTimestamp;
import org.bson.BsonValue;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.lang.Nullable;
@@ -45,7 +42,6 @@ import com.mongodb.client.model.changestream.FullDocument;
* @author Mark Paluch
* @since 2.1
*/
@EqualsAndHashCode
public class ChangeStreamOptions {
private @Nullable Object filter;
@@ -156,6 +152,44 @@ public class ChangeStreamOptions {
+ ObjectUtils.nullSafeClassName(timestamp));
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ChangeStreamOptions that = (ChangeStreamOptions) o;
if (!ObjectUtils.nullSafeEquals(this.filter, that.filter)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.resumeToken, that.resumeToken)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.fullDocumentLookup, that.fullDocumentLookup)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.collation, that.collation)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.resumeTimestamp, that.resumeTimestamp)) {
return false;
}
return resume == that.resume;
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(filter);
result = 31 * result + ObjectUtils.nullSafeHashCode(resumeToken);
result = 31 * result + ObjectUtils.nullSafeHashCode(fullDocumentLookup);
result = 31 * result + ObjectUtils.nullSafeHashCode(collation);
result = 31 * result + ObjectUtils.nullSafeHashCode(resumeTimestamp);
result = 31 * result + ObjectUtils.nullSafeHashCode(resume);
return result;
}
/**
* @author Christoph Strobl
* @since 2.2

View File

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

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.RequiredArgsConstructor;
import java.util.Optional;
import org.springframework.data.mongodb.core.query.Collation;
@@ -95,7 +93,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(int)}.
* <strong>NOTE</strong> Using capped collections requires defining {@link #size(long)}.
*
* @return new {@link CollectionOptions}.
* @since 2.0
@@ -312,7 +310,6 @@ public class CollectionOptions {
* @author Andreas Zink
* @since 2.1
*/
@RequiredArgsConstructor
public static class ValidationOptions {
private static final ValidationOptions NONE = new ValidationOptions(null, null, null);
@@ -321,6 +318,13 @@ public class CollectionOptions {
private final @Nullable ValidationLevel validationLevel;
private final @Nullable ValidationAction validationAction;
public ValidationOptions(Validator validator, ValidationLevel validationLevel, ValidationAction validationAction) {
this.validator = validator;
this.validationLevel = validationLevel;
this.validationAction = validationAction;
}
/**
* Create an empty {@link ValidationOptions}.
*

View File

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

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.NonNull;
import lombok.Value;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -27,11 +24,13 @@ import java.util.stream.Collectors;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.data.mongodb.BulkOperationException;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.convert.UpdateMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
@@ -46,7 +45,9 @@ import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.util.Pair;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.WriteConcern;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.MongoCollection;
@@ -62,6 +63,8 @@ import com.mongodb.client.model.*;
* @author Minsu Kim
* @author Jens Schauder
* @author Michail Nikolaev
* @author Roman Puchkovskiy
* @author Jacob Botuck
* @since 1.9
*/
class DefaultBulkOperations implements BulkOperations {
@@ -71,7 +74,6 @@ class DefaultBulkOperations implements BulkOperations {
private final BulkOperationContext bulkOperationContext;
private final List<SourceAwareWriteModelHolder> models = new ArrayList<>();
private PersistenceExceptionTranslator exceptionTranslator;
private @Nullable WriteConcern defaultWriteConcern;
private BulkWriteOptions bulkOptions;
@@ -95,19 +97,9 @@ class DefaultBulkOperations implements BulkOperations {
this.mongoOperations = mongoOperations;
this.collectionName = collectionName;
this.bulkOperationContext = bulkOperationContext;
this.exceptionTranslator = new MongoExceptionTranslator();
this.bulkOptions = getBulkWriteOptions(bulkOperationContext.getBulkMode());
}
/**
* Configures the {@link PersistenceExceptionTranslator} to be used. Defaults to {@link MongoExceptionTranslator}.
*
* @param exceptionTranslator can be {@literal null}.
*/
public void setExceptionTranslator(@Nullable PersistenceExceptionTranslator exceptionTranslator) {
this.exceptionTranslator = exceptionTranslator == null ? new MongoExceptionTranslator() : exceptionTranslator;
}
/**
* Configures the default {@link WriteConcern} to be used. Defaults to {@literal null}.
*
@@ -300,6 +292,7 @@ class DefaultBulkOperations implements BulkOperations {
Assert.state(result != null, "Result must not be null.");
models.forEach(this::maybeEmitAfterSaveEvent);
models.forEach(this::maybeInvokeAfterSaveCallback);
return result;
} finally {
@@ -313,11 +306,26 @@ class DefaultBulkOperations implements BulkOperations {
collection = collection.withWriteConcern(defaultWriteConcern);
}
return collection.bulkWrite( //
models.stream() //
.map(this::extractAndMapWriteModel) //
.collect(Collectors.toList()), //
bulkOptions);
try {
return collection.bulkWrite( //
models.stream() //
.map(this::extractAndMapWriteModel) //
.collect(Collectors.toList()), //
bulkOptions);
} catch (RuntimeException ex) {
if (ex instanceof MongoBulkWriteException) {
MongoBulkWriteException mongoBulkWriteException = (MongoBulkWriteException) ex;
if (mongoBulkWriteException.getWriteConcernError() != null) {
throw new DataIntegrityViolationException(ex.getMessage(), ex);
}
throw new BulkOperationException(ex.getMessage(), mongoBulkWriteException);
}
throw ex;
}
}
private WriteModel<Document> extractAndMapWriteModel(SourceAwareWriteModelHolder it) {
@@ -421,38 +429,52 @@ class DefaultBulkOperations implements BulkOperations {
models.add(new SourceAwareWriteModelHolder(source, model));
}
private void maybeEmitBeforeSaveEvent(SourceAwareWriteModelHolder it) {
private void maybeEmitBeforeSaveEvent(SourceAwareWriteModelHolder holder) {
if (it.getModel() instanceof InsertOneModel) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) it.getModel()).getDocument();
maybeEmitEvent(new BeforeSaveEvent<>(it.getSource(), target, collectionName));
} else if (it.getModel() instanceof ReplaceOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) it.getModel()).getReplacement();
maybeEmitEvent(new BeforeSaveEvent<>(it.getSource(), target, collectionName));
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
}
}
private void maybeEmitAfterSaveEvent(SourceAwareWriteModelHolder it) {
private void maybeEmitAfterSaveEvent(SourceAwareWriteModelHolder holder) {
if (it.getModel() instanceof InsertOneModel) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) it.getModel()).getDocument();
maybeEmitEvent(new AfterSaveEvent<>(it.getSource(), target, collectionName));
} else if (it.getModel() instanceof ReplaceOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeEmitEvent(new AfterSaveEvent<>(holder.getSource(), target, collectionName));
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) it.getModel()).getReplacement();
maybeEmitEvent(new AfterSaveEvent<>(it.getSource(), target, collectionName));
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeEmitEvent(new AfterSaveEvent<>(holder.getSource(), target, collectionName));
}
}
private void maybeInvokeAfterSaveCallback(SourceAwareWriteModelHolder holder) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeInvokeAfterSaveCallback(holder.getSource(), target);
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeInvokeAfterSaveCallback(holder.getSource(), target);
}
}
private <E extends MongoMappingEvent<T>, T> E maybeEmitEvent(E event) {
if (null != bulkOperationContext.getEventPublisher()) {
bulkOperationContext.getEventPublisher().publishEvent(event);
if (bulkOperationContext.getEventPublisher() == null) {
return event;
}
bulkOperationContext.getEventPublisher().publishEvent(event);
return event;
}
@@ -475,6 +497,16 @@ class DefaultBulkOperations implements BulkOperations {
collectionName);
}
private Object maybeInvokeAfterSaveCallback(Object value, Document mappedDocument) {
if (bulkOperationContext.getEntityCallbacks() == null) {
return value;
}
return bulkOperationContext.getEntityCallbacks().callback(AfterSaveCallback.class, value, mappedDocument,
collectionName);
}
private static BulkWriteOptions getBulkWriteOptions(BulkMode bulkMode) {
BulkWriteOptions options = new BulkWriteOptions();
@@ -520,15 +552,93 @@ class DefaultBulkOperations implements BulkOperations {
* @author Christoph Strobl
* @since 2.0
*/
@Value
static class BulkOperationContext {
static final class BulkOperationContext {
@NonNull BulkMode bulkMode;
@NonNull Optional<? extends MongoPersistentEntity<?>> entity;
@NonNull QueryMapper queryMapper;
@NonNull UpdateMapper updateMapper;
ApplicationEventPublisher eventPublisher;
EntityCallbacks entityCallbacks;
private final BulkMode bulkMode;
private final Optional<? extends MongoPersistentEntity<?>> entity;
private final QueryMapper queryMapper;
private final UpdateMapper updateMapper;
private final ApplicationEventPublisher eventPublisher;
private final EntityCallbacks entityCallbacks;
BulkOperationContext(BulkOperations.BulkMode bulkMode, Optional<? extends MongoPersistentEntity<?>> entity,
QueryMapper queryMapper, UpdateMapper updateMapper, ApplicationEventPublisher eventPublisher,
EntityCallbacks entityCallbacks) {
this.bulkMode = bulkMode;
this.entity = entity;
this.queryMapper = queryMapper;
this.updateMapper = updateMapper;
this.eventPublisher = eventPublisher;
this.entityCallbacks = entityCallbacks;
}
public BulkMode getBulkMode() {
return this.bulkMode;
}
public Optional<? extends MongoPersistentEntity<?>> getEntity() {
return this.entity;
}
public QueryMapper getQueryMapper() {
return this.queryMapper;
}
public UpdateMapper getUpdateMapper() {
return this.updateMapper;
}
public ApplicationEventPublisher getEventPublisher() {
return this.eventPublisher;
}
public EntityCallbacks getEntityCallbacks() {
return this.entityCallbacks;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BulkOperationContext that = (BulkOperationContext) o;
if (bulkMode != that.bulkMode)
return false;
if (!ObjectUtils.nullSafeEquals(this.entity, that.entity)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.queryMapper, that.queryMapper)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.updateMapper, that.updateMapper)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.eventPublisher, that.eventPublisher)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.entityCallbacks, that.entityCallbacks);
}
@Override
public int hashCode() {
int result = bulkMode != null ? bulkMode.hashCode() : 0;
result = 31 * result + ObjectUtils.nullSafeHashCode(entity);
result = 31 * result + ObjectUtils.nullSafeHashCode(queryMapper);
result = 31 * result + ObjectUtils.nullSafeHashCode(updateMapper);
result = 31 * result + ObjectUtils.nullSafeHashCode(eventPublisher);
result = 31 * result + ObjectUtils.nullSafeHashCode(entityCallbacks);
return result;
}
public String toString() {
return "DefaultBulkOperations.BulkOperationContext(bulkMode=" + this.getBulkMode() + ", entity="
+ this.getEntity() + ", queryMapper=" + this.getQueryMapper() + ", updateMapper=" + this.getUpdateMapper()
+ ", eventPublisher=" + this.getEventPublisher() + ", entityCallbacks=" + this.getEntityCallbacks() + ")";
}
}
/**
@@ -537,10 +647,50 @@ class DefaultBulkOperations implements BulkOperations {
* @since 2.2
* @author Christoph Strobl
*/
@Value
private static class SourceAwareWriteModelHolder {
private static final class SourceAwareWriteModelHolder {
Object source;
WriteModel<Document> model;
private final Object source;
private final WriteModel<Document> model;
SourceAwareWriteModelHolder(Object source, WriteModel<Document> model) {
this.source = source;
this.model = model;
}
public Object getSource() {
return this.source;
}
public WriteModel<Document> getModel() {
return this.model;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SourceAwareWriteModelHolder that = (SourceAwareWriteModelHolder) o;
if (!ObjectUtils.nullSafeEquals(this.source, that.source)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.model, that.model);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(model);
result = 31 * result + ObjectUtils.nullSafeHashCode(source);
return result;
}
public String toString() {
return "DefaultBulkOperations.SourceAwareWriteModelHolder(source=" + this.getSource() + ", model="
+ this.getModel() + ")";
}
}
}

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. {@MongoException}s will be caught and translated by the calling MongoTemplate An
* about exception handling. {@link 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

@@ -15,10 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
@@ -55,21 +51,24 @@ import org.springframework.util.MultiValueMap;
* @see MongoTemplate
* @see ReactiveMongoTemplate
*/
@RequiredArgsConstructor
class EntityOperations {
private static final String ID_FIELD = "_id";
private final @NonNull MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context;
EntityOperations(MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context) {
this.context = context;
}
/**
* Creates a new {@link Entity} for the given bean.
*
* @param entity must not be {@literal null}.
* @return
* @return new instance of {@link Entity}.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> Entity<T> forEntity(T entity) {
<T> Entity<T> forEntity(T entity) {
Assert.notNull(entity, "Bean must not be null!");
@@ -89,10 +88,10 @@ class EntityOperations {
*
* @param entity must not be {@literal null}.
* @param conversionService must not be {@literal null}.
* @return
* @return new instance of {@link AdaptibleEntity}.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> AdaptibleEntity<T> forEntity(T entity, ConversionService conversionService) {
<T> AdaptibleEntity<T> forEntity(T entity, ConversionService conversionService) {
Assert.notNull(entity, "Bean must not be null!");
Assert.notNull(conversionService, "ConversionService must not be null!");
@@ -108,6 +107,10 @@ 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) {
@@ -138,7 +141,7 @@ class EntityOperations {
* {@code _id} if no identifier property can be found.
*
* @param type must not be {@literal null}.
* @return
* @return never {@literal null}.
*/
public String getIdPropertyName(Class<?> type) {
@@ -342,11 +345,14 @@ class EntityOperations {
Number getVersion();
}
@RequiredArgsConstructor
private static class UnmappedEntity<T extends Map<String, Object>> implements AdaptibleEntity<T> {
private final T map;
protected UnmappedEntity(T map) {
this.map = map;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.EntityOperations.PersistableSource#getIdPropertyName()
@@ -456,7 +462,7 @@ class EntityOperations {
private static class SimpleMappedEntity<T extends Map<String, Object>> extends UnmappedEntity<T> {
SimpleMappedEntity(T map) {
protected SimpleMappedEntity(T map) {
super(map);
}
@@ -479,12 +485,19 @@ class EntityOperations {
}
}
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
private static class MappedEntity<T> implements Entity<T> {
private final @NonNull MongoPersistentEntity<?> entity;
private final @NonNull IdentifierAccessor idAccessor;
private final @NonNull PersistentPropertyAccessor<T> propertyAccessor;
private final MongoPersistentEntity<?> entity;
private final IdentifierAccessor idAccessor;
private final PersistentPropertyAccessor<T> propertyAccessor;
protected MappedEntity(MongoPersistentEntity<?> entity, IdentifierAccessor idAccessor,
PersistentPropertyAccessor<T> propertyAccessor) {
this.entity = entity;
this.idAccessor = idAccessor;
this.propertyAccessor = propertyAccessor;
}
private static <T> MappedEntity<T> of(T bean,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context) {
@@ -755,11 +768,12 @@ class EntityOperations {
* {@link TypedOperations} for generic entities that are not represented with {@link PersistentEntity} (e.g. custom
* conversions).
*/
@RequiredArgsConstructor
enum UntypedOperations implements TypedOperations<Object> {
INSTANCE;
UntypedOperations() {}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> TypedOperations<T> instance() {
return (TypedOperations) INSTANCE;
@@ -794,10 +808,13 @@ class EntityOperations {
*
* @param <T>
*/
@RequiredArgsConstructor
static class TypedEntityOperations<T> implements TypedOperations<T> {
private final @NonNull MongoPersistentEntity<T> entity;
private final MongoPersistentEntity<T> entity;
protected TypedEntityOperations(MongoPersistentEntity<T> entity) {
this.entity = entity;
}
/*
* (non-Javadoc)

View File

@@ -88,9 +88,9 @@ 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.Cursor}
* Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable}
*
* @return a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.Cursor} that needs to be closed.
* @return a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs to be closed.
* Never {@literal null}.
*/
CloseableIterator<T> stream();

View File

@@ -15,16 +15,10 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.util.CloseableIterator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -35,10 +29,13 @@ import org.springframework.util.StringUtils;
* @author Mark Paluch
* @since 2.0
*/
@RequiredArgsConstructor
class ExecutableAggregationOperationSupport implements ExecutableAggregationOperation {
private final @NonNull MongoTemplate template;
private final MongoTemplate template;
ExecutableAggregationOperationSupport(MongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -56,15 +53,21 @@ class ExecutableAggregationOperationSupport implements ExecutableAggregationOper
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ExecutableAggregationSupport<T>
implements AggregationWithAggregation<T>, ExecutableAggregation<T>, TerminatingAggregation<T> {
@NonNull MongoTemplate template;
@NonNull Class<T> domainType;
@Nullable Aggregation aggregation;
@Nullable String collection;
private final MongoTemplate template;
private final Class<T> domainType;
private final Aggregation aggregation;
private final String collection;
public ExecutableAggregationSupport(MongoTemplate template, Class<T> domainType, Aggregation aggregation,
String collection) {
this.template = template;
this.domainType = domainType;
this.aggregation = aggregation;
this.collection = collection;
}
/*
* (non-Javadoc)

View File

@@ -21,6 +21,7 @@ import java.util.stream.Stream;
import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.lang.Nullable;
@@ -43,7 +44,7 @@ import com.mongodb.client.MongoCollection;
* query(Human.class)
* .inCollection("star-wars")
* .as(Jedi.class)
* .matching(query(where("firstname").is("luke")))
* .matching(where("firstname").is("luke"))
* .all();
* </code>
* </pre>
@@ -117,7 +118,7 @@ public interface ExecutableFindOperation {
/**
* Stream all matching elements.
*
* @return a {@link Stream} that wraps the a Mongo DB {@link com.mongodb.Cursor} that needs to be closed. Never
* @return a {@link Stream} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs to be closed. Never
* {@literal null}.
*/
Stream<T> stream();
@@ -170,6 +171,18 @@ public interface ExecutableFindOperation {
*/
TerminatingFind<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingFind}.
* @throws IllegalArgumentException if criteria is {@literal null}.
* @since 3.0
*/
default TerminatingFind<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
/**
* Set the filter query for the geoNear execution.
*
@@ -291,9 +304,21 @@ public interface ExecutableFindOperation {
*
* @param query must not be {@literal null}.
* @return new instance of {@link TerminatingDistinct}.
* @throws IllegalArgumentException if resultType is {@literal null}.
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingDistinct<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingDistinct}.
* @throws IllegalArgumentException if criteria is {@literal null}.
* @since 3.0
*/
default TerminatingDistinct<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,12 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import com.mongodb.ReadPreference;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
@@ -37,6 +31,7 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import com.mongodb.ReadPreference;
import com.mongodb.client.FindIterable;
/**
@@ -46,12 +41,15 @@ import com.mongodb.client.FindIterable;
* @author Mark Paluch
* @since 2.0
*/
@RequiredArgsConstructor
class ExecutableFindOperationSupport implements ExecutableFindOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull MongoTemplate template;
private final MongoTemplate template;
ExecutableFindOperationSupport(MongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -70,16 +68,23 @@ class ExecutableFindOperationSupport implements ExecutableFindOperation {
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ExecutableFindSupport<T>
implements ExecutableFind<T>, FindWithCollection<T>, FindWithProjection<T>, FindWithQuery<T> {
@NonNull MongoTemplate template;
@NonNull Class<?> domainType;
Class<T> returnType;
@Nullable String collection;
Query query;
private final MongoTemplate template;
private final Class<?> domainType;
private final Class<T> returnType;
@Nullable private final String collection;
private final Query query;
ExecutableFindSupport(MongoTemplate template, Class<?> domainType, Class<T> returnType,
String collection, Query query) {
this.template = template;
this.domainType = domainType;
this.returnType = returnType;
this.collection = collection;
this.query = query;
}
/*
* (non-Javadoc)
@@ -257,9 +262,9 @@ class ExecutableFindOperationSupport implements ExecutableFindOperation {
* @see org.springframework.data.mongodb.core.CursorPreparer#prepare(com.mongodb.clientFindIterable)
*/
@Override
public FindIterable<Document> prepare(FindIterable<Document> cursor) {
public FindIterable<Document> prepare(FindIterable<Document> iterable) {
FindIterable<Document> target = delegate != null ? delegate.prepare(cursor) : cursor;
FindIterable<Document> target = delegate != null ? delegate.prepare(iterable) : iterable;
return limit.map(target::limit).orElse(target);
}

View File

@@ -15,11 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import java.util.ArrayList;
import java.util.Collection;
@@ -37,10 +32,13 @@ import com.mongodb.bulk.BulkWriteResult;
* @author Mark Paluch
* @since 2.0
*/
@RequiredArgsConstructor
class ExecutableInsertOperationSupport implements ExecutableInsertOperation {
private final @NonNull MongoTemplate template;
private final MongoTemplate template;
ExecutableInsertOperationSupport(MongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -58,14 +56,20 @@ class ExecutableInsertOperationSupport implements ExecutableInsertOperation {
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ExecutableInsertSupport<T> implements ExecutableInsert<T> {
@NonNull MongoTemplate template;
@NonNull Class<T> domainType;
@Nullable String collection;
@Nullable BulkMode bulkMode;
private final MongoTemplate template;
private final Class<T> domainType;
@Nullable private final String collection;
@Nullable private final BulkMode bulkMode;
ExecutableInsertSupport(MongoTemplate template, Class<T> domainType, String collection, BulkMode bulkMode) {
this.template = template;
this.domainType = domainType;
this.collection = collection;
this.bulkMode = bulkMode;
}
/*
* (non-Javadoc)

View File

@@ -19,6 +19,7 @@ import java.util.List;
import org.springframework.data.mongodb.core.ExecutableFindOperation.ExecutableFind;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
/**
@@ -30,7 +31,7 @@ import org.springframework.data.mongodb.core.query.Query;
* The collection to operate on is by default derived from the initial {@literal domainType} and can be defined there
* via {@link org.springframework.data.mongodb.core.mapping.Document}. Using {@code inCollection} allows to override the
* collection name for the execution.
*
*
* <pre>
* <code>
* mapReduce(Human.class)
@@ -44,6 +45,7 @@ import org.springframework.data.mongodb.core.query.Query;
* </pre>
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 2.1
*/
public interface ExecutableMapReduceOperation {
@@ -146,6 +148,18 @@ public interface ExecutableMapReduceOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingMapReduce<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingMapReduce}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default TerminatingMapReduce<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.List;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
@@ -32,12 +29,17 @@ import org.springframework.util.StringUtils;
* @author Christoph Strobl
* @since 2.1
*/
@RequiredArgsConstructor
class ExecutableMapReduceOperationSupport implements ExecutableMapReduceOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull MongoTemplate template;
private final MongoTemplate template;
ExecutableMapReduceOperationSupport(MongoTemplate template) {
Assert.notNull(template, "Template must not be null!");
this.template = template;
}
/*
* (non-Javascript)

View File

@@ -17,6 +17,7 @@ package org.springframework.data.mongodb.core;
import java.util.List;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import com.mongodb.client.result.DeleteResult;
@@ -119,6 +120,18 @@ public interface ExecutableRemoveOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingRemove<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingRemove}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default TerminatingRemove<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,11 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
@@ -36,12 +31,15 @@ import com.mongodb.client.result.DeleteResult;
* @author Mark Paluch
* @since 2.0
*/
@RequiredArgsConstructor
class ExecutableRemoveOperationSupport implements ExecutableRemoveOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull MongoTemplate tempate;
private final MongoTemplate tempate;
public ExecutableRemoveOperationSupport(MongoTemplate tempate) {
this.tempate = tempate;
}
/*
* (non-Javadoc)
@@ -59,14 +57,19 @@ class ExecutableRemoveOperationSupport implements ExecutableRemoveOperation {
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ExecutableRemoveSupport<T> implements ExecutableRemove<T>, RemoveWithCollection<T> {
@NonNull MongoTemplate template;
@NonNull Class<T> domainType;
Query query;
@Nullable String collection;
private final MongoTemplate template;
private final Class<T> domainType;
private final Query query;
@Nullable private final String collection;
public ExecutableRemoveSupport(MongoTemplate template, Class<T> domainType, Query query, String collection) {
this.template = template;
this.domainType = domainType;
this.query = query;
this.collection = collection;
}
/*
* (non-Javadoc)

View File

@@ -18,6 +18,7 @@ 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.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
@@ -210,6 +211,18 @@ public interface ExecutableUpdateOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
UpdateWithUpdate<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link UpdateWithUpdate}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default UpdateWithUpdate<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,11 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
@@ -35,12 +30,15 @@ import com.mongodb.client.result.UpdateResult;
* @author Mark Paluch
* @since 2.0
*/
@RequiredArgsConstructor
class ExecutableUpdateOperationSupport implements ExecutableUpdateOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull MongoTemplate template;
private final MongoTemplate template;
ExecutableUpdateOperationSupport(MongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -58,21 +56,34 @@ class ExecutableUpdateOperationSupport implements ExecutableUpdateOperation {
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ExecutableUpdateSupport<T>
implements ExecutableUpdate<T>, UpdateWithCollection<T>, UpdateWithQuery<T>, TerminatingUpdate<T>,
FindAndReplaceWithOptions<T>, TerminatingFindAndReplace<T>, FindAndReplaceWithProjection<T> {
@NonNull MongoTemplate template;
@NonNull Class domainType;
Query query;
@Nullable UpdateDefinition update;
@Nullable String collection;
@Nullable FindAndModifyOptions findAndModifyOptions;
@Nullable FindAndReplaceOptions findAndReplaceOptions;
@Nullable Object replacement;
@NonNull Class<T> targetType;
private final MongoTemplate template;
private final Class domainType;
private final Query query;
@Nullable private final UpdateDefinition update;
@Nullable private final String collection;
@Nullable private final FindAndModifyOptions findAndModifyOptions;
@Nullable private final FindAndReplaceOptions findAndReplaceOptions;
@Nullable private final Object replacement;
private final Class<T> targetType;
ExecutableUpdateSupport(MongoTemplate template, Class domainType, Query query, UpdateDefinition update,
String collection, FindAndModifyOptions findAndModifyOptions, FindAndReplaceOptions findAndReplaceOptions,
Object replacement, Class<T> targetType) {
this.template = template;
this.domainType = domainType;
this.query = query;
this.update = update;
this.collection = collection;
this.findAndModifyOptions = findAndModifyOptions;
this.findAndReplaceOptions = findAndReplaceOptions;
this.replacement = replacement;
this.targetType = targetType;
}
/*
* (non-Javadoc)

View File

@@ -78,7 +78,7 @@ public class FindAndModifyOptions {
}
/**
* Create new {@link FindAndModifyOptions} based on option of given {@litearl source}.
* Create new {@link FindAndModifyOptions} based on option of given {@literal 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
* @return
* @param collation can be {@literal null}.
* @return this.
* @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
* @return never {@literal null}.
* @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
* @return {@literal true} if set.
*/
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
* @return {@literal true} if set.
*/
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
* @return never {@literal null}.
* @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
* @return never {@literal null}.
*/
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
* @return never {@literal null}, uses {@link Double#NaN} if {@literal avgDistance} does not exist.
* @see <a href="https://jira.mongodb.org/browse/SERVER-21024">MongoDB Jira SERVER-21024</a>
*/
public double getAverageDistance() {

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
import java.util.List;
@@ -27,8 +24,6 @@ import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.util.StreamUtils;
import com.mongodb.client.model.Filters;
/**
* A MongoDB document in its mapped state. I.e. after a source document has been mapped using mapping information of the
* entity the source document was supposed to represent.
@@ -36,13 +31,20 @@ import com.mongodb.client.model.Filters;
* @author Oliver Gierke
* @since 2.1
*/
@RequiredArgsConstructor(staticName = "of")
public class MappedDocument {
private static final String ID_FIELD = "_id";
private static final Document ID_ONLY_PROJECTION = new Document(ID_FIELD, 1);
private final @Getter Document document;
private final Document document;
private MappedDocument(Document document) {
this.document = document;
}
public static MappedDocument of(Document document) {
return new MappedDocument(document);
}
public static Document getIdOnlyProjection() {
return ID_ONLY_PROJECTION;
@@ -91,6 +93,10 @@ public class MappedDocument {
return new MappedUpdate(Update.fromDocument(document, ID_FIELD));
}
public Document getDocument() {
return this.document;
}
/**
* An {@link UpdateDefinition} that indicates that the {@link #getUpdateObject() update object} has already been
* mapped to the specific domain type.

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.Value;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
@@ -24,6 +22,7 @@ import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.SessionAwareMethodInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.mongodb.ClientSessionOptions;
import com.mongodb.WriteConcern;
@@ -171,11 +170,15 @@ public abstract class MongoDatabaseFactorySupport<C> implements MongoDatabaseFac
* @author Christoph Strobl
* @since 2.1
*/
@Value
static class ClientSessionBoundMongoDbFactory implements MongoDatabaseFactory {
static final class ClientSessionBoundMongoDbFactory implements MongoDatabaseFactory {
ClientSession session;
MongoDatabaseFactory delegate;
private final ClientSession session;
private final MongoDatabaseFactory delegate;
public ClientSessionBoundMongoDbFactory(ClientSession session, MongoDatabaseFactory delegate) {
this.session = session;
this.delegate = delegate;
}
/*
* (non-Javadoc)
@@ -254,7 +257,42 @@ public abstract class MongoDatabaseFactorySupport<C> implements MongoDatabaseFac
factory.addAdvice(new SessionAwareMethodInterceptor<>(session, target, ClientSession.class, MongoDatabase.class,
this::proxyDatabase, MongoCollection.class, this::proxyCollection));
return targetType.cast(factory.getProxy());
return targetType.cast(factory.getProxy(target.getClass().getClassLoader()));
}
public ClientSession getSession() {
return this.session;
}
public MongoDatabaseFactory getDelegate() {
return this.delegate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClientSessionBoundMongoDbFactory that = (ClientSessionBoundMongoDbFactory) o;
if (!ObjectUtils.nullSafeEquals(this.session, that.session)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.delegate, that.delegate);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(this.session);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.delegate);
return result;
}
public String toString() {
return "MongoDatabaseFactorySupport.ClientSessionBoundMongoDbFactory(session=" + this.getSession() + ", delegate="
+ this.getDelegate() + ")";
}
}
}

View File

@@ -79,7 +79,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
* @return never {@literal null}.
*/
String getCollectionName(Class<?> entityClass);
@@ -363,7 +363,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Returns the {@link ScriptOperations} that can be performed on {@link com.mongodb.client.MongoDatabase} level.
*
* @return
* @return never {@literal null}.
* @since 1.7
* @deprecated since 2.2. The {@code eval} command has been removed without replacement in MongoDB Server 4.2.0.
*/
@@ -1184,6 +1184,29 @@ public interface MongoOperations extends FluentMongoOperations {
*/
long count(Query query, String collectionName);
/**
* Estimate the number of documents, in the collection {@link #getCollectionName(Class) identified by the given type},
* based on collection statistics.
*
* @param entityClass must not be {@literal null}.
* @return the estimated number of documents.
* @since 3.1
*/
default long estimatedCount(Class<?> entityClass) {
Assert.notNull(entityClass, "Entity class must not be null!");
return estimatedCount(getCollectionName(entityClass));
}
/**
* Estimate the number of documents in the given collection based on collection statistics.
*
* @param collectionName must not be {@literal null}.
* @return the estimated number of documents.
* @since 3.1
*/
long estimatedCount(String collectionName);
/**
* Returns the number of documents for the given {@link Query} by querying the given collection using the given entity
* class to map the given {@link Query}. <br />
@@ -1557,7 +1580,7 @@ public interface MongoOperations extends FluentMongoOperations {
/**
* Returns the underlying {@link MongoConverter}.
*
* @return
* @return never {@literal null}.
*/
MongoConverter getConverter();
}

View File

@@ -17,11 +17,6 @@ package org.springframework.data.mongodb.core;
import static org.springframework.data.mongodb.core.query.SerializationUtils.*;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -33,6 +28,7 @@ import org.bson.Document;
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;
@@ -87,20 +83,12 @@ import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCre
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent;
import org.springframework.data.mongodb.core.mapping.event.*;
import org.springframework.data.mongodb.core.mapreduce.GroupBy;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Meta;
@@ -166,6 +154,8 @@ import com.mongodb.client.result.UpdateResult;
* @author Andreas Zink
* @author Cimon Lucas
* @author Michael J. Simons
* @author Roman Puchkovskiy
* @author Yadhukrishna S Pai
*/
public class MongoTemplate implements MongoOperations, ApplicationContextAware, IndexOperationsProvider {
@@ -245,7 +235,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
this.projectionFactory = new SpelAwareProxyProjectionFactory();
this.operations = new EntityOperations(this.mongoConverter.getMappingContext());
this.propertyOperations = new PropertyOperations(this.mongoConverter.getMappingContext());
this.queryOperations = new QueryOperations(queryMapper, updateMapper, operations, mongoDbFactory);
this.queryOperations = new QueryOperations(queryMapper, updateMapper, operations, propertyOperations,
mongoDbFactory);
// We always have a mapping context in the converter, whether it's a simple one or not
mappingContext = this.mongoConverter.getMappingContext();
@@ -431,8 +422,10 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
MongoPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(entityType);
Document mappedFields = getMappedFieldsObject(query.getFieldsObject(), persistentEntity, returnType);
Document mappedQuery = queryMapper.getMappedObject(query.getQueryObject(), persistentEntity);
QueryContext queryContext = queryOperations.createQueryContext(query);
Document mappedQuery = queryContext.getMappedQuery(persistentEntity);
Document mappedFields = queryContext.getMappedFields(persistentEntity, returnType, projectionFactory);
FindIterable<Document> cursor = new QueryCursorPreparer(query, entityType).initiateFind(collection,
col -> col.find(mappedQuery, Document.class).projection(mappedFields));
@@ -766,7 +759,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
new BulkOperationContext(mode, Optional.ofNullable(getPersistentEntity(entityType)), queryMapper, updateMapper,
eventPublisher, entityCallbacks));
operations.setExceptionTranslator(exceptionTranslator);
operations.setDefaultWriteConcern(writeConcern);
return operations;
@@ -1061,7 +1053,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
QueryContext queryContext = queryOperations.createQueryContext(query);
Document mappedQuery = queryContext.getMappedQuery(entity);
Document mappedFields = queryContext.getMappedFields(entity);
Document mappedFields = queryContext.getMappedFields(entity, resultType, projectionFactory);
Document mappedSort = queryContext.getMappedSort(entity);
replacement = maybeCallBeforeConvert(replacement, collectionName);
@@ -1070,8 +1062,15 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
maybeEmitEvent(new BeforeSaveEvent<>(replacement, mappedReplacement, collectionName));
maybeCallBeforeSave(replacement, mappedReplacement, collectionName);
return doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort,
T saved = doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort,
queryContext.getCollation(entityType).orElse(null), entityType, mappedReplacement, options, resultType);
if (saved != null) {
maybeEmitEvent(new AfterSaveEvent<>(saved, mappedReplacement, collectionName));
return maybeCallAfterSave(saved, mappedReplacement, collectionName);
}
return saved;
}
// Find methods that take a Query to express the query and that return a single object that is also removed from the
@@ -1136,6 +1135,19 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
collection -> collection.countDocuments(CountQuery.of(filter).toQueryDocument(), options));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#estimatedCount(java.lang.String)
*/
@Override
public long estimatedCount(String collectionName) {
return doEstimatedCount(collectionName, new EstimatedDocumentCountOptions());
}
protected long doEstimatedCount(String collectionName, EstimatedDocumentCountOptions options) {
return execute(collectionName, collection -> collection.estimatedDocumentCount(options));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#insert(java.lang.Object)
@@ -1165,7 +1177,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
protected void ensureNotIterable(@Nullable Object o) {
if (null != o) {
if (o != null) {
if (o.getClass().isArray() || ITERABLE_CLASSES.contains(o.getClass().getName())) {
throw new IllegalArgumentException("Cannot use a collection here.");
}
@@ -1174,7 +1186,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
/**
* Prepare the collection before any processing is done using it. This allows a convenient way to apply settings like
* slaveOk() etc. Can be overridden in sub-classes.
* withCodecRegistry() etc. Can be overridden in sub-classes.
*
* @param collection
*/
@@ -1233,8 +1245,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
T saved = populateIdIfNecessary(initialized, id);
maybeEmitEvent(new AfterSaveEvent<>(saved, dbDoc, collectionName));
return saved;
return maybeCallAfterSave(saved, dbDoc, collectionName);
}
@Override
@@ -1327,8 +1338,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
if (i < ids.size()) {
T saved = populateIdIfNecessary(obj, ids.get(i));
maybeEmitEvent(new AfterSaveEvent<>(saved, documentList.get(i), collectionName));
savedObjects.add(saved);
Document doc = documentList.get(i);
maybeEmitEvent(new AfterSaveEvent<>(saved, doc, collectionName));
savedObjects.add(maybeCallAfterSave(saved, doc, collectionName));
} else {
savedObjects.add(obj);
}
@@ -1398,7 +1410,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
maybeEmitEvent(new AfterSaveEvent<>(toSave, mapped.getDocument(), collectionName));
return toSave;
return maybeCallAfterSave(toSave, mapped.getDocument(), collectionName);
}
protected <T> T doSave(String collectionName, T objectToSave, MongoWriter<T> writer) {
@@ -1419,7 +1431,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
T saved = populateIdIfNecessary(objectToSave, id);
maybeEmitEvent(new AfterSaveEvent<>(saved, dbDoc, collectionName));
return saved;
return maybeCallAfterSave(saved, dbDoc, collectionName);
}
@SuppressWarnings("ConstantConditions")
@@ -1819,7 +1831,11 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
if (query.getMeta().getMaxTimeMsec() != null) {
mapReduce = mapReduce.maxTime(query.getMeta().getMaxTimeMsec(), TimeUnit.MILLISECONDS);
}
mapReduce = mapReduce.sort(getMappedSortObject(query, domainType));
Document mappedSort = getMappedSortObject(query, domainType);
if (mappedSort != null && !mappedSort.isEmpty()) {
mapReduce = mapReduce.sort(getMappedSortObject(query, domainType));
}
mapReduce = mapReduce
.filter(queryMapper.getMappedObject(query.getQueryObject(), mappingContext.getPersistentEntity(domainType)));
@@ -1961,9 +1977,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
AggregationOperationContext context = new TypeBasedAggregationOperationContext(aggregation.getInputType(),
mappingContext, queryMapper);
return aggregate(aggregation, inputCollectionName, outputType, context);
return aggregate(aggregation, inputCollectionName, outputType, null);
}
/* (non-Javadoc)
@@ -2117,7 +2131,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
List<Document> rawResult = new ArrayList<>();
Class<?> domainType = aggregation instanceof TypedAggregation ? ((TypedAggregation) aggregation).getInputType()
Class<?> domainType = aggregation instanceof TypedAggregation ? ((TypedAggregation<?>) aggregation).getInputType()
: null;
Optional<Collation> collation = Optionals.firstNonEmpty(options::getCollation,
@@ -2133,11 +2147,23 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
options.getComment().ifPresent(aggregateIterable::comment);
options.getHint().ifPresent(aggregateIterable::hint);
if (options.hasExecutionTimeLimit()) {
aggregateIterable = aggregateIterable.maxTime(options.getMaxTime().toMillis(), TimeUnit.MILLISECONDS);
}
if (options.isSkipResults()) {
// toCollection only allowed for $out and $merge if those are the last stages
if (aggregation.getPipeline().isOutOrMerge()) {
aggregateIterable.toCollection();
} else {
aggregateIterable.first();
}
return new AggregationResults<>(Collections.emptyList(), new Document());
}
MongoIterable<O> iterable = aggregateIterable.map(val -> {
rawResult.add(val);
@@ -2180,6 +2206,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
}
options.getComment().ifPresent(cursor::comment);
options.getHint().ifPresent(cursor::hint);
Class<?> domainType = aggregation instanceof TypedAggregation ? ((TypedAggregation) aggregation).getInputType()
: null;
@@ -2305,33 +2332,49 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
protected <E extends MongoMappingEvent<T>, T> E maybeEmitEvent(E event) {
if (null != eventPublisher) {
if (eventPublisher != null) {
eventPublisher.publishEvent(event);
}
return event;
}
@SuppressWarnings("unchecked")
protected <T> T maybeCallBeforeConvert(T object, String collection) {
if (null != entityCallbacks) {
if (entityCallbacks != null) {
return entityCallbacks.callback(BeforeConvertCallback.class, object, collection);
}
return object;
}
@SuppressWarnings("unchecked")
protected <T> T maybeCallBeforeSave(T object, Document document, String collection) {
if (null != entityCallbacks) {
if (entityCallbacks != null) {
return entityCallbacks.callback(BeforeSaveCallback.class, object, document, collection);
}
return object;
}
protected <T> T maybeCallAfterSave(T object, Document document, String collection) {
if (entityCallbacks != null) {
return entityCallbacks.callback(AfterSaveCallback.class, object, document, collection);
}
return object;
}
protected <T> T maybeCallAfterConvert(T object, Document document, String collection) {
if (entityCallbacks != null) {
return entityCallbacks.callback(AfterConvertCallback.class, object, document, collection);
}
return object;
}
/**
* Create the specified collection using the provided options
*
@@ -2419,8 +2462,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
Document mappedFields = queryMapper.getMappedObject(fields, entity);
QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
Document mappedFields = queryContext.getMappedFields(entity, entityClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("findOne using query: {} fields: {} for class: {} in collection: {}", serializeToJsonSafely(query),
@@ -2470,8 +2514,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
Document mappedFields = queryMapper.getMappedFields(fields, entity);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
Document mappedFields = queryContext.getMappedFields(entity, entityClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("find using query: {} fields: {} for class: {} in collection: {}",
@@ -2493,8 +2538,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(sourceClass);
Document mappedFields = getMappedFieldsObject(fields, entity, targetClass);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
Document mappedFields = queryContext.getMappedFields(entity, targetClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("find using query: {} fields: {} for class: {} in collection: {}",
@@ -2823,23 +2869,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
return queryMapper.getMappedSort(query.getSortObject(), mappingContext.getPersistentEntity(type));
}
private Document getMappedFieldsObject(Document fields, @Nullable MongoPersistentEntity<?> entity,
Class<?> targetType) {
if (entity == null) {
return fields;
}
Document projectedFields = propertyOperations.computeFieldsForProjection(projectionFactory, fields,
entity.getType(), targetType);
if (ObjectUtils.nullSafeEquals(fields, projectedFields)) {
return queryMapper.getMappedFields(projectedFields, entity);
}
return queryMapper.getMappedFields(projectedFields, mappingContext.getRequiredPersistentEntity(targetType));
}
/**
* Tries to convert the given {@link RuntimeException} into a {@link DataAccessException} but returns the original
* exception if the conversation failed. Thus allows safe re-throwing of the return value.
@@ -2940,12 +2969,17 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
private class ExistsCallback implements CollectionCallback<Boolean> {
private final Document mappedQuery;
private final com.mongodb.client.model.Collation collation;
ExistsCallback(Document mappedQuery, com.mongodb.client.model.Collation collation) {
this.mappedQuery = mappedQuery;
this.collation = collation;
}
@Override
public Boolean doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
@@ -2967,7 +3001,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
private final Document sort;
private final Optional<Collation> collation;
public FindAndRemoveCallback(Document query, Document fields, Document sort, @Nullable Collation collation) {
FindAndRemoveCallback(Document query, Document fields, Document sort, @Nullable Collation collation) {
this.query = query;
this.fields = fields;
@@ -2993,8 +3027,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
private final List<Document> arrayFilters;
private final FindAndModifyOptions options;
public FindAndModifyCallback(Document query, Document fields, Document sort, Object update,
List<Document> arrayFilters, FindAndModifyOptions options) {
FindAndModifyCallback(Document query, Document fields, Document sort, Object update, List<Document> arrayFilters,
FindAndModifyOptions options) {
this.query = query;
this.fields = fields;
this.sort = sort;
@@ -3101,25 +3136,34 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Roman Puchkovskiy
*/
@RequiredArgsConstructor
private class ReadDocumentCallback<T> implements DocumentCallback<T> {
private final @NonNull EntityReader<? super T, Bson> reader;
private final @NonNull Class<T> type;
private final EntityReader<? super T, Bson> reader;
private final Class<T> type;
private final String collectionName;
@Nullable
public T doWith(@Nullable Document object) {
ReadDocumentCallback(EntityReader<? super T, Bson> reader, Class<T> type, String collectionName) {
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, type, collectionName));
this.reader = reader;
this.type = type;
this.collectionName = collectionName;
}
@Nullable
public T doWith(@Nullable Document document) {
T source = null;
if (document != null) {
maybeEmitEvent(new AfterLoadEvent<>(document, type, collectionName));
source = reader.read(type, document);
}
T source = reader.read(type, object);
if (null != source) {
maybeEmitEvent(new AfterConvertEvent<>(object, source, collectionName));
if (source != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, source, collectionName));
source = maybeCallAfterConvert(source, document, collectionName);
}
return source;
@@ -3134,13 +3178,21 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @param <T>
* @since 2.0
*/
@RequiredArgsConstructor
private class ProjectingReadCallback<S, T> implements DocumentCallback<T> {
private final @NonNull EntityReader<Object, Bson> reader;
private final @NonNull Class<S> entityType;
private final @NonNull Class<T> targetType;
private final @NonNull String collectionName;
private final EntityReader<Object, Bson> reader;
private final Class<S> entityType;
private final Class<T> targetType;
private final String collectionName;
ProjectingReadCallback(EntityReader<Object, Bson> reader, Class<S> entityType, Class<T> targetType,
String collectionName) {
this.reader = reader;
this.entityType = entityType;
this.targetType = targetType;
this.collectionName = collectionName;
}
/*
* (non-Javadoc)
@@ -3148,24 +3200,23 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
*/
@SuppressWarnings("unchecked")
@Nullable
public T doWith(@Nullable Document object) {
public T doWith(@Nullable Document document) {
if (object == null) {
if (document == null) {
return null;
}
Class<?> typeToRead = targetType.isInterface() || targetType.isAssignableFrom(entityType) ? entityType
: targetType;
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, targetType, collectionName));
}
maybeEmitEvent(new AfterLoadEvent<>(document, targetType, collectionName));
Object source = reader.read(typeToRead, object);
Object source = reader.read(typeToRead, document);
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, source) : source;
if (null != result) {
maybeEmitEvent(new AfterConvertEvent<>(object, result, collectionName));
if (result != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, result, collectionName));
result = maybeCallAfterConvert(result, document, collectionName);
}
return (T) result;
@@ -3177,7 +3228,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
private final Query query;
private final @Nullable Class<?> type;
public QueryCursorPreparer(Query query, @Nullable Class<?> type) {
QueryCursorPreparer(Query query, @Nullable Class<?> type) {
this.query = query;
this.type = type;
@@ -3187,9 +3238,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> cursor) {
public FindIterable<Document> prepare(FindIterable<Document> iterable) {
FindIterable<Document> cursorToUse = cursor;
FindIterable<Document> cursorToUse = iterable;
operations.forType(type).getCollation(query) //
.map(Collation::toMongoCollation) //
@@ -3248,6 +3299,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
case PARTIAL:
cursorToUse = cursorToUse.partial(true);
break;
case SECONDARY_READS:
case SLAVE_OK:
break;
default:
@@ -3265,7 +3317,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
@Override
public ReadPreference getReadPreference() {
return query.getMeta().getFlags().contains(CursorOption.SLAVE_OK) ? ReadPreference.primaryPreferred() : null;
return (query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS)
|| query.getMeta().getFlags().contains(CursorOption.SLAVE_OK)) ? ReadPreference.primaryPreferred() : null;
}
}
@@ -3319,7 +3372,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @author Thomas Darimont
* @since 1.7
*/
@AllArgsConstructor(access = AccessLevel.PACKAGE)
static class CloseableIterableCursorAdapter<T> implements CloseableIterator<T> {
private volatile @Nullable MongoCursor<Document> cursor;
@@ -3333,14 +3385,22 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @param exceptionTranslator
* @param objectReadCallback
*/
public CloseableIterableCursorAdapter(MongoIterable<Document> cursor,
PersistenceExceptionTranslator exceptionTranslator, DocumentCallback<T> objectReadCallback) {
CloseableIterableCursorAdapter(MongoIterable<Document> cursor, PersistenceExceptionTranslator exceptionTranslator,
DocumentCallback<T> objectReadCallback) {
this.cursor = cursor.iterator();
this.exceptionTranslator = exceptionTranslator;
this.objectReadCallback = objectReadCallback;
}
CloseableIterableCursorAdapter(MongoCursor<Document> cursor, PersistenceExceptionTranslator exceptionTranslator,
DocumentCallback<T> objectReadCallback) {
this.cursor = cursor;
this.exceptionTranslator = exceptionTranslator;
this.objectReadCallback = objectReadCallback;
}
@Override
public boolean hasNext() {

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.bson.Document;
import org.springframework.data.mapping.SimplePropertyHandler;
import org.springframework.data.mapping.context.MappingContext;
@@ -33,11 +30,14 @@ import org.springframework.util.ClassUtils;
* @author Christoph Strobl
* @since 2.1
*/
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class PropertyOperations {
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
PropertyOperations(MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
this.mappingContext = mappingContext;
}
/**
* For cases where {@code fields} is {@link Document#isEmpty() empty} include only fields that are required for
* creating the projection (target) type if the {@code targetType} is a {@literal DTO projection} or a

View File

@@ -47,8 +47,10 @@ import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import com.mongodb.client.model.CountOptions;
@@ -70,6 +72,7 @@ class QueryOperations {
private final QueryMapper queryMapper;
private final UpdateMapper updateMapper;
private final EntityOperations entityOperations;
private final PropertyOperations propertyOperations;
private final CodecRegistryProvider codecRegistryProvider;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
private final AggregationUtil aggregationUtil;
@@ -81,14 +84,16 @@ class QueryOperations {
* @param queryMapper must not be {@literal null}.
* @param updateMapper must not be {@literal null}.
* @param entityOperations must not be {@literal null}.
* @param propertyOperations must not be {@literal null}.
* @param codecRegistryProvider must not be {@literal null}.
*/
QueryOperations(QueryMapper queryMapper, UpdateMapper updateMapper, EntityOperations entityOperations,
CodecRegistryProvider codecRegistryProvider) {
PropertyOperations propertyOperations, CodecRegistryProvider codecRegistryProvider) {
this.queryMapper = queryMapper;
this.updateMapper = updateMapper;
this.entityOperations = entityOperations;
this.propertyOperations = propertyOperations;
this.codecRegistryProvider = codecRegistryProvider;
this.mappingContext = queryMapper.getMappingContext();
this.aggregationUtil = new AggregationUtil(queryMapper, mappingContext);
@@ -250,14 +255,31 @@ class QueryOperations {
return queryMapper.getMappedObject(getQueryObject(), entity);
}
/**
* Get the already mapped {@link Query#getFieldsObject() fields projection}
*
* @param entity the Entity to map field names to. Can be {@literal null}.
* @return never {@literal null}.
*/
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity) {
return queryMapper.getMappedFields(query.getFieldsObject(), entity);
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity, Class<?> targetType,
ProjectionFactory projectionFactory) {
Document fields = query.getFieldsObject();
Document mappedFields = fields;
if (entity == null) {
return mappedFields;
}
Document projectedFields = propertyOperations.computeFieldsForProjection(projectionFactory, fields,
entity.getType(), targetType);
if (ObjectUtils.nullSafeEquals(fields, projectedFields)) {
mappedFields = queryMapper.getMappedFields(projectedFields, entity);
} else {
mappedFields = queryMapper.getMappedFields(projectedFields,
mappingContext.getRequiredPersistentEntity(targetType));
}
if (entity != null && entity.hasTextScoreProperty() && !query.getQueryObject().containsKey("$text")) {
mappedFields.remove(entity.getTextScoreProperty().getFieldName());
}
return mappedFields;
}
/**
@@ -319,6 +341,10 @@ class QueryOperations {
}
@Override
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity, Class<?> targetType, ProjectionFactory projectionFactory) {
return getMappedFields(entity);
}
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity) {
return queryMapper.getMappedFields(new Document(fieldName, 1), entity);
}
@@ -681,10 +707,9 @@ class QueryOperations {
*/
List<Document> getUpdatePipeline(@Nullable Class<?> domainType) {
AggregationOperationContext context = domainType != null
? new RelaxedTypeBasedAggregationOperationContext(domainType, mappingContext, queryMapper)
: Aggregation.DEFAULT_CONTEXT;
Class<?> type = domainType != null ? domainType : Object.class;
AggregationOperationContext context = new RelaxedTypeBasedAggregationOperationContext(type, mappingContext, queryMapper);
return aggregationUtil.createPipeline((AggregationUpdate) update, context);
}

View File

@@ -15,10 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import reactor.core.publisher.Flux;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
@@ -62,15 +58,22 @@ class ReactiveAggregationOperationSupport implements ReactiveAggregationOperatio
return new ReactiveAggregationSupport<>(template, domainType, null, null);
}
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ReactiveAggregationSupport<T>
implements AggregationOperationWithAggregation<T>, ReactiveAggregation<T>, TerminatingAggregationOperation<T> {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<T> domainType;
Aggregation aggregation;
String collection;
private final ReactiveMongoTemplate template;
private final Class<T> domainType;
private final Aggregation aggregation;
private final String collection;
ReactiveAggregationSupport(ReactiveMongoTemplate template, Class<T> domainType, Aggregation aggregation,
String collection) {
this.template = template;
this.domainType = domainType;
this.aggregation = aggregation;
this.collection = collection;
}
/*
* (non-Javadoc)

View File

@@ -19,6 +19,7 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
@@ -38,13 +39,14 @@ import org.springframework.data.mongodb.core.query.Query;
* query(Human.class)
* .inCollection("star-wars")
* .as(Jedi.class)
* .matching(query(where("firstname").is("luke")))
* .matching(where("firstname").is("luke"))
* .all();
* </code>
* </pre>
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Juergen Zimmermann
* @since 2.0
*/
public interface ReactiveFindOperation {
@@ -144,6 +146,18 @@ public interface ReactiveFindOperation {
*/
TerminatingFind<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingFind}.
* @throws IllegalArgumentException if criteria is {@literal null}.
* @since 3.0
*/
default TerminatingFind<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
/**
* Set the filter query for the geoNear execution.
*
@@ -259,9 +273,21 @@ public interface ReactiveFindOperation {
*
* @param query must not be {@literal null}.
* @return new instance of {@link TerminatingDistinct}.
* @throws IllegalArgumentException if resultType is {@literal null}.
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingDistinct<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingDistinct}.
* @throws IllegalArgumentException if criteria is {@literal null}.
* @since 3.0
*/
default TerminatingDistinct<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,15 +15,10 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
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;
@@ -39,12 +34,15 @@ import org.springframework.util.StringUtils;
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
class ReactiveFindOperationSupport implements ReactiveFindOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull ReactiveMongoTemplate template;
private final ReactiveMongoTemplate template;
ReactiveFindOperationSupport(ReactiveMongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -64,16 +62,24 @@ class ReactiveFindOperationSupport implements ReactiveFindOperation {
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ReactiveFindSupport<T>
implements ReactiveFind<T>, FindWithCollection<T>, FindWithProjection<T>, FindWithQuery<T> {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<?> domainType;
Class<T> returnType;
String collection;
Query query;
private final ReactiveMongoTemplate template;
private final Class<?> domainType;
private final Class<T> returnType;
private final String collection;
private final Query query;
ReactiveFindSupport(ReactiveMongoTemplate template, Class<?> domainType, Class<T> returnType,
String collection, Query query) {
this.template = template;
this.domainType = domainType;
this.returnType = returnType;
this.collection = collection;
this.query = query;
}
/*
* (non-Javadoc)

View File

@@ -15,10 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -34,10 +30,13 @@ import org.springframework.util.StringUtils;
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
class ReactiveInsertOperationSupport implements ReactiveInsertOperation {
private final @NonNull ReactiveMongoTemplate template;
private final ReactiveMongoTemplate template;
ReactiveInsertOperationSupport(ReactiveMongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -51,13 +50,18 @@ class ReactiveInsertOperationSupport implements ReactiveInsertOperation {
return new ReactiveInsertSupport<>(template, domainType, null);
}
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ReactiveInsertSupport<T> implements ReactiveInsert<T> {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<T> domainType;
String collection;
private final ReactiveMongoTemplate template;
private final Class<T> domainType;
private final String collection;
ReactiveInsertSupport(ReactiveMongoTemplate template, Class<T> domainType, String collection) {
this.template = template;
this.domainType = domainType;
this.collection = collection;
}
/*
* (non-Javadoc)

View File

@@ -19,6 +19,7 @@ import reactor.core.publisher.Flux;
import org.springframework.data.mongodb.core.ExecutableFindOperation.ExecutableFind;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
/**
@@ -30,7 +31,7 @@ import org.springframework.data.mongodb.core.query.Query;
* The collection to operate on is by default derived from the initial {@literal domainType} and can be defined there
* via {@link org.springframework.data.mongodb.core.mapping.Document}. Using {@code inCollection} allows to override the
* collection name for the execution.
*
*
* <pre>
* <code>
* mapReduce(Human.class)
@@ -146,6 +147,18 @@ public interface ReactiveMapReduceOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingMapReduce<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingMapReduce}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default TerminatingMapReduce<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
@@ -31,12 +29,15 @@ import org.springframework.util.StringUtils;
* @author Christoph Strobl
* @since 2.1
*/
@RequiredArgsConstructor
class ReactiveMapReduceOperationSupport implements ReactiveMapReduceOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull ReactiveMongoTemplate template;
private final ReactiveMongoTemplate template;
ReactiveMapReduceOperationSupport(ReactiveMongoTemplate template) {
this.template = template;
}
/*
* (non-Javascript)

View File

@@ -15,11 +15,15 @@
*/
package org.springframework.data.mongodb.core;
import org.reactivestreams.Publisher;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.springframework.util.Assert;
import com.mongodb.reactivestreams.client.ClientSession;
/**
@@ -29,7 +33,7 @@ import com.mongodb.reactivestreams.client.ClientSession;
* @author Christoph Strobl
* @author Mark Paluch
* @since 2.1
* @see Mono#subscriberContext()
* @see Mono#deferContextual(Function)
* @see Context
*/
public class ReactiveMongoContext {
@@ -46,8 +50,14 @@ public class ReactiveMongoContext {
*/
public static Mono<ClientSession> getSession() {
return Mono.subscriberContext().filter(ctx -> ctx.hasKey(SESSION_KEY))
.flatMap(ctx -> ctx.<Mono<ClientSession>> get(SESSION_KEY));
return Mono.deferContextual(ctx -> {
if (ctx.hasKey(SESSION_KEY)) {
return ctx.<Mono<ClientSession>> get(SESSION_KEY);
}
return Mono.empty();
});
}
/**

View File

@@ -66,6 +66,7 @@ import com.mongodb.reactivestreams.client.MongoCollection;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.0
* @see Flux
* @see Mono
@@ -298,7 +299,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* @param collectionName name of the collection.
* @return an existing collection or one created on first server interaction.
*/
MongoCollection<Document> getCollection(String collectionName);
Mono<MongoCollection<Document>> getCollection(String collectionName);
/**
* Check to see if a collection with a name indicated by the entity class exists.
@@ -979,6 +980,29 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
*/
Mono<Long> count(Query query, @Nullable Class<?> entityClass, String collectionName);
/**
* Estimate the number of documents, in the collection {@link #getCollectionName(Class) identified by the given type},
* based on collection statistics.
*
* @param entityClass must not be {@literal null}.
* @return a {@link Mono} emitting the estimated number of documents.
* @since 3.1
*/
default Mono<Long> estimatedCount(Class<?> entityClass) {
Assert.notNull(entityClass, "Entity class must not be null!");
return estimatedCount(getCollectionName(entityClass));
}
/**
* Estimate the number of documents in the given collection based on collection statistics.
*
* @param collectionName must not be {@literal null}.
* @return a {@link Mono} emitting the estimated number of documents.
* @since 3.1
*/
Mono<Long> estimatedCount(String collectionName);
/**
* Insert the object into the collection for the entity type of the object to save.
* <p/>
@@ -1238,7 +1262,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* 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.
* 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}.
@@ -1571,7 +1595,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
/**
* Returns the underlying {@link MongoConverter}.
*
* @return
* @return never {@literal null}.
*/
MongoConverter getConverter();
@@ -1579,7 +1603,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
* @return never {@literal null}.
* @since 2.1
*/
String getCollectionName(Class<?> entityClass);

View File

@@ -17,9 +17,7 @@ package org.springframework.data.mongodb.core;
import static org.springframework.data.mongodb.core.query.SerializationUtils.*;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
@@ -39,6 +37,7 @@ 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;
@@ -91,17 +90,9 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoSimpleTypes;
import org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent;
import org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.*;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Meta;
import org.springframework.data.mongodb.core.query.Meta.CursorOption;
@@ -127,16 +118,7 @@ import com.mongodb.CursorType;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.model.CountOptions;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.DeleteOptions;
import com.mongodb.client.model.FindOneAndDeleteOptions;
import com.mongodb.client.model.FindOneAndReplaceOptions;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReplaceOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.ValidationOptions;
import com.mongodb.client.model.*;
import com.mongodb.client.model.changestream.FullDocument;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertOneResult;
@@ -163,6 +145,9 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Roman Puchkovskiy
* @author Mathieu Ouellet
* @author Yadhukrishna S Pai
* @since 2.0
*/
public class ReactiveMongoTemplate implements ReactiveMongoOperations, ApplicationContextAware {
@@ -265,7 +250,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
this.mappingContext = this.mongoConverter.getMappingContext();
this.operations = new EntityOperations(this.mappingContext);
this.propertyOperations = new PropertyOperations(this.mappingContext);
this.queryOperations = new QueryOperations(queryMapper, updateMapper, operations, mongoDatabaseFactory);
this.queryOperations = new QueryOperations(queryMapper, updateMapper, operations, propertyOperations,
mongoDatabaseFactory);
// We create indexes based on mapping events
if (this.mappingContext instanceof MongoMappingContext) {
@@ -324,8 +310,7 @@ 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 MongoDatabaseFactory} will apply. If you configured a {@link Mongo} instance no
* {@link WriteConcern} will be used.
* configured on the {@link MongoDatabaseFactory} will apply.
*
* @param writeConcern can be {@literal null}.
*/
@@ -589,7 +574,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
ReactiveMongoTemplate.this);
return Flux.from(action.doInSession(operations)) //
.subscriberContext(ctx -> ReactiveMongoContext.setSession(ctx, Mono.just(session)));
.contextWrite(ctx -> ReactiveMongoContext.setSession(ctx, Mono.just(session)));
}
/*
@@ -724,15 +709,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#getCollection(java.lang.String)
*/
public MongoCollection<Document> getCollection(String collectionName) {
public Mono<MongoCollection<Document>> getCollection(String collectionName) {
Assert.notNull(collectionName, "Collection name must not be null!");
try {
return this.mongoDatabaseFactory.getMongoDatabase().getCollection(collectionName);
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
}
return createMono(db -> Mono.just(db.getCollection(collectionName)));
}
/*
@@ -783,7 +764,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
return createFlux(MongoDatabase::listCollectionNames);
}
public MongoDatabase getMongoDatabase() {
public Mono<MongoDatabase> getMongoDatabase() {
return mongoDatabaseFactory.getMongoDatabase();
}
@@ -1026,11 +1007,14 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
}
ReadDocumentCallback<O> readCallback = new ReadDocumentCallback<>(mongoConverter, outputType, collectionName);
return execute(collectionName, collection -> aggregateAndMap(collection, pipeline, options, readCallback,
aggregation instanceof TypedAggregation ? ((TypedAggregation) aggregation).getInputType() : null));
return execute(collectionName,
collection -> aggregateAndMap(collection, pipeline, aggregation.getPipeline().isOutOrMerge(), options,
readCallback,
aggregation instanceof TypedAggregation ? ((TypedAggregation<?>) aggregation).getInputType() : null));
}
private <O> Flux<O> aggregateAndMap(MongoCollection<Document> collection, List<Document> pipeline,
boolean isOutOrMerge,
AggregationOptions options, ReadDocumentCallback<O> readCallback, @Nullable Class<?> inputType) {
AggregatePublisher<Document> cursor = collection.aggregate(pipeline, Document.class)
@@ -1041,6 +1025,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
}
options.getComment().ifPresent(cursor::comment);
options.getHint().ifPresent(cursor::hint);
Optionals.firstNonEmpty(options::getCollation, () -> operations.forType(inputType).getCollation()) //
.map(Collation::toMongoCollation) //
@@ -1050,7 +1035,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
cursor = cursor.maxTime(options.getMaxTime().toMillis(), TimeUnit.MILLISECONDS);
}
return Flux.from(cursor).map(readCallback::doWith);
if (options.isSkipResults()) {
return (isOutOrMerge ? Flux.from(cursor.toCollection()) : Flux.from(cursor.first())).thenMany(Mono.empty());
}
return Flux.from(cursor).concatMap(readCallback::doWith);
}
/*
@@ -1093,7 +1082,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
.withOptions(AggregationOptions.builder().collation(near.getCollation()).build());
return aggregate($geoNear, collection, Document.class) //
.map(callback::doWith);
.concatMap(callback::doWith);
}
/*
@@ -1168,28 +1157,33 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
QueryContext queryContext = queryOperations.createQueryContext(query);
Document mappedQuery = queryContext.getMappedQuery(entity);
Document mappedFields = queryContext.getMappedFields(entity);
Document mappedFields = queryContext.getMappedFields(entity, resultType, projectionFactory);
Document mappedSort = queryContext.getMappedSort(entity);
return Mono.just(PersistableEntityModel.of(replacement, collectionName)) //
.doOnNext(it -> maybeEmitEvent(new BeforeConvertEvent<>(it.getSource(), it.getCollection()))) //
.flatMap(it -> maybeCallBeforeConvert(it.getSource(), it.getCollection()).map(it::mutate))
.map(it -> it
.addTargetDocument(operations.forEntity(it.getSource()).toMappedDocument(mongoConverter).getDocument())) //
.doOnNext(it -> maybeEmitEvent(new BeforeSaveEvent(it.getSource(), it.getTarget(), it.getCollection()))) //
.flatMap(it -> {
return Mono.defer(() -> {
PersistableEntityModel<S> flowObject = (PersistableEntityModel<S>) it;
return maybeCallBeforeSave(flowObject.getSource(), flowObject.getTarget(), flowObject.getCollection())
.map(potentiallyModified -> PersistableEntityModel.of(potentiallyModified, flowObject.getTarget(),
flowObject.getCollection()));
}).flatMap(it -> {
PersistableEntityModel<S> pem = PersistableEntityModel.of(replacement, collectionName);
PersistableEntityModel<S> flowObject = (PersistableEntityModel<S>) it;
return doFindAndReplace(flowObject.getCollection(), mappedQuery, mappedFields, mappedSort,
queryContext.getCollation(entityType).orElse(null), entityType, flowObject.getTarget(), options,
resultType);
maybeEmitEvent(new BeforeConvertEvent<>(pem.getSource(), pem.getCollection()));
return maybeCallBeforeConvert(pem.getSource(), pem.getCollection()).map(pem::mutate).flatMap(it -> {
PersistableEntityModel<S> mapped = it
.addTargetDocument(operations.forEntity(it.getSource()).toMappedDocument(mongoConverter).getDocument());
maybeEmitEvent(new BeforeSaveEvent(mapped.getSource(), mapped.getTarget(), mapped.getCollection()));
return maybeCallBeforeSave(it.getSource(), mapped.getTarget(), mapped.getCollection())
.map(potentiallyModified -> PersistableEntityModel.of(potentiallyModified, mapped.getTarget(),
mapped.getCollection()));
}).flatMap(it -> {
Mono<T> afterFindAndReplace = doFindAndReplace(it.getCollection(), mappedQuery, mappedFields, mappedSort,
queryContext.getCollation(entityType).orElse(null), entityType, it.getTarget(), options, resultType);
return afterFindAndReplace.flatMap(saved -> {
maybeEmitEvent(new AfterSaveEvent<>(saved, it.getTarget(), it.getCollection()));
return maybeCallAfterSave(saved, it.getTarget(), it.getCollection());
});
});
});
}
/*
@@ -1255,6 +1249,15 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
});
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#estimatedCount(java.lang.String)
*/
@Override
public Mono<Long> estimatedCount(String collectionName) {
return doEstimatedCount(collectionName, new EstimatedDocumentCountOptions());
}
/**
* Run the actual count operation against the collection with given name.
*
@@ -1269,6 +1272,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
collection -> collection.countDocuments(CountQuery.of(filter).toQueryDocument(), options));
}
protected Mono<Long> doEstimatedCount(String collectionName, EstimatedDocumentCountOptions options) {
return createMono(collectionName, collection -> collection.estimatedDocumentCount(options));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#insert(reactor.core.publisher.Mono)
@@ -1336,21 +1344,22 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
AdaptibleEntity<T> entity = operations.forEntity(it.getSource(), mongoConverter.getConversionService());
entity.assertUpdateableIdIfNotSet();
return PersistableEntityModel.of(entity.initializeVersionProperty(),
PersistableEntityModel<T> model = PersistableEntityModel.of(entity.initializeVersionProperty(),
entity.toMappedDocument(writer).getDocument(), it.getCollection());
}).doOnNext(it -> maybeEmitEvent(new BeforeSaveEvent<>(it.getSource(), it.getTarget(), it.getCollection()))) //
maybeEmitEvent(new BeforeSaveEvent<>(model.getSource(), model.getTarget(), model.getCollection()));
return model;
})//
.flatMap(it -> {
return maybeCallBeforeSave(it.getSource(), it.getTarget(), it.getCollection()).map(it::mutate);
}).flatMap(it -> {
return insertDocument(it.getCollection(), it.getTarget(), it.getSource().getClass()).map(id -> {
return insertDocument(it.getCollection(), it.getTarget(), it.getSource().getClass()).flatMap(id -> {
T saved = operations.forEntity(it.getSource(), mongoConverter.getConversionService())
.populateIdIfNecessary(id);
maybeEmitEvent(new AfterSaveEvent<>(saved, it.getTarget(), collectionName));
return saved;
return maybeCallAfterSave(saved, it.getTarget(), collectionName);
});
});
}
@@ -1436,13 +1445,14 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
return insertDocumentList(collectionName, documents).thenMany(Flux.fromIterable(tuples));
});
return insertDocuments.map(tuple -> {
return insertDocuments.flatMap(tuple -> {
Object id = MappedDocument.of(tuple.getT2()).getId();
Document document = tuple.getT2();
Object id = MappedDocument.of(document).getId();
T saved = tuple.getT1().populateIdIfNecessary(id);
maybeEmitEvent(new AfterSaveEvent<>(saved, tuple.getT2(), collectionName));
return saved;
maybeEmitEvent(new AfterSaveEvent<>(saved, document, collectionName));
return maybeCallAfterSave(saved, document, collectionName);
});
}
@@ -1522,9 +1532,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
maybeEmitEvent(new BeforeSaveEvent<>(toConvert, document, collectionName));
return maybeCallBeforeSave(toConvert, document, collectionName).flatMap(it -> {
return doUpdate(collectionName, query, mapped.updateWithoutId(), it.getClass(), false, false).map(result -> {
return maybeEmitEvent(new AfterSaveEvent<T>(it, document, collectionName)).getSource();
});
return doUpdate(collectionName, query, mapped.updateWithoutId(), it.getClass(), false, false)
.flatMap(result -> {
maybeEmitEvent(new AfterSaveEvent<T>(it, document, collectionName));
return maybeCallAfterSave(it, document, collectionName);
});
});
});
});
@@ -1546,10 +1558,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
return maybeCallBeforeSave(toConvert, dbDoc, collectionName).flatMap(it -> {
return saveDocument(collectionName, dbDoc, it.getClass()).map(id -> {
return saveDocument(collectionName, dbDoc, it.getClass()).flatMap(id -> {
T saved = entity.populateIdIfNecessary(id);
return maybeEmitEvent(new AfterSaveEvent<>(saved, dbDoc, collectionName)).getSource();
maybeEmitEvent(new AfterSaveEvent<>(saved, dbDoc, collectionName));
return maybeCallAfterSave(saved, dbDoc, collectionName);
});
});
});
@@ -2070,24 +2083,25 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
FullDocument fullDocument = ClassUtils.isAssignable(Document.class, targetType) ? FullDocument.DEFAULT
: FullDocument.UPDATE_LOOKUP;
MongoDatabase db = StringUtils.hasText(database) ? mongoDatabaseFactory.getMongoDatabase(database)
: getMongoDatabase();
return ReactiveMongoDatabaseUtils.getDatabase(database, mongoDatabaseFactory) //
.map(db -> {
ChangeStreamPublisher<Document> publisher;
if (StringUtils.hasText(collectionName)) {
publisher = filter.isEmpty() ? db.getCollection(collectionName).watch(Document.class)
: db.getCollection(collectionName).watch(filter, Document.class);
ChangeStreamPublisher<Document> publisher;
if (StringUtils.hasText(collectionName)) {
publisher = filter.isEmpty() ? db.getCollection(collectionName).watch(Document.class)
: db.getCollection(collectionName).watch(filter, Document.class);
} else {
publisher = filter.isEmpty() ? db.watch(Document.class) : db.watch(filter, Document.class);
}
} else {
publisher = filter.isEmpty() ? db.watch(Document.class) : db.watch(filter, Document.class);
}
publisher = options.getResumeToken().map(BsonValue::asDocument).map(publisher::resumeAfter).orElse(publisher);
publisher = options.getCollation().map(Collation::toMongoCollation).map(publisher::collation).orElse(publisher);
publisher = options.getResumeBsonTimestamp().map(publisher::startAtOperationTime).orElse(publisher);
publisher = publisher.fullDocument(options.getFullDocumentLookup().orElse(fullDocument));
return Flux.from(publisher).map(document -> new ChangeStreamEvent<>(document, targetType, getConverter()));
publisher = options.getResumeToken().map(BsonValue::asDocument).map(publisher::resumeAfter).orElse(publisher);
publisher = options.getCollation().map(Collation::toMongoCollation).map(publisher::collation)
.orElse(publisher);
publisher = options.getResumeBsonTimestamp().map(publisher::startAtOperationTime).orElse(publisher);
return publisher.fullDocument(options.getFullDocumentLookup().orElse(fullDocument));
}) //
.flatMapMany(publisher -> Flux.from(publisher)
.map(document -> new ChangeStreamEvent<>(document, targetType, getConverter())));
}
List<Document> prepareFilter(ChangeStreamOptions options) {
@@ -2099,7 +2113,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
AggregationOperationContext context = agg instanceof TypedAggregation
? new TypeBasedAggregationOperationContext(((TypedAggregation<?>) agg).getInputType(),
getConverter().getMappingContext(), queryMapper)
: Aggregation.DEFAULT_CONTEXT;
: new RelaxedTypeBasedAggregationOperationContext(Object.class, mappingContext, queryMapper);
return agg.toPipeline(new PrefixingDelegatingAggregationOperationContext(context, "fullDocument",
Arrays.asList("operationType", "fullDocument", "documentKey", "updateDescription", "ns")));
@@ -2149,7 +2163,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
MapReducePublisher<Document> publisher = collection.mapReduce(mapFunction, reduceFunction, Document.class);
publisher.filter(mappedQuery);
publisher.sort(getMappedSortObject(filterQuery, domainType));
Document mappedSort = getMappedSortObject(filterQuery, domainType);
if (mappedSort != null && !mappedSort.isEmpty()) {
publisher.sort(mappedSort);
}
if (filterQuery.getMeta().getMaxTimeMsec() != null) {
publisher.maxTime(filterQuery.getMeta().getMaxTimeMsec(), TimeUnit.MILLISECONDS);
@@ -2213,7 +2231,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
publisher = collation.map(Collation::toMongoCollation).map(publisher::collation).orElse(publisher);
return Flux.from(publisher)
.map(new ReadDocumentCallback<>(mongoConverter, resultType, inputCollectionName)::doWith);
.concatMap(new ReadDocumentCallback<>(mongoConverter, resultType, inputCollectionName)::doWith);
});
}
@@ -2329,7 +2347,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
LOGGER.debug("Created collection [{}]", collectionName);
}
}).thenReturn(getCollection(collectionName));
}).then(getCollection(collectionName));
}
/**
@@ -2366,8 +2384,11 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
Class<T> entityClass, FindPublisherPreparer preparer) {
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
Document mappedFields = fields == null ? null : queryMapper.getMappedObject(fields, entity);
QueryContext queryContext = queryOperations
.createQueryContext(new BasicQuery(query, fields != null ? fields : new Document()));
Document mappedFields = queryContext.getMappedFields(entity, entityClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("findOne using query: %s fields: %s for class: %s in collection: %s",
@@ -2402,8 +2423,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 DBCursor} used when iterating over the result set, (apply
* limits, skips and so on).
* @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).
* @return the {@link List} of converted objects.
*/
protected <T> Flux<T> doFind(String collectionName, Document query, Document fields, Class<T> entityClass,
@@ -2417,8 +2438,9 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
Document mappedFields = queryMapper.getMappedFields(fields, entity);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
Document mappedFields = queryContext.getMappedFields(entity, entityClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("find using query: %s fields: %s for class: %s in collection: %s",
@@ -2440,8 +2462,9 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(sourceClass);
Document mappedFields = getMappedFieldsObject(fields, entity, targetClass);
Document mappedQuery = queryMapper.getMappedObject(query, entity);
QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
Document mappedFields = queryContext.getMappedFields(entity, targetClass, projectionFactory);
Document mappedQuery = queryContext.getMappedQuery(entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("find using query: {} fields: {} for class: {} in collection: {}",
@@ -2606,33 +2629,49 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
protected <E extends MongoMappingEvent<T>, T> E maybeEmitEvent(E event) {
if (null != eventPublisher) {
if (eventPublisher != null) {
eventPublisher.publishEvent(event);
}
return event;
}
@SuppressWarnings("unchecked")
protected <T> Mono<T> maybeCallBeforeConvert(T object, String collection) {
if (null != entityCallbacks) {
if (entityCallbacks != null) {
return entityCallbacks.callback(ReactiveBeforeConvertCallback.class, object, collection);
}
return Mono.just(object);
}
@SuppressWarnings("unchecked")
protected <T> Mono<T> maybeCallBeforeSave(T object, Document document, String collection) {
if (null != entityCallbacks) {
if (entityCallbacks != null) {
return entityCallbacks.callback(ReactiveBeforeSaveCallback.class, object, document, collection);
}
return Mono.just(object);
}
protected <T> Mono<T> maybeCallAfterSave(T object, Document document, String collection) {
if (entityCallbacks != null) {
return entityCallbacks.callback(ReactiveAfterSaveCallback.class, object, document, collection);
}
return Mono.just(object);
}
protected <T> Mono<T> maybeCallAfterConvert(T object, Document document, String collection) {
if (entityCallbacks != null) {
return entityCallbacks.callback(ReactiveAfterConvertCallback.class, object, document, collection);
}
return Mono.just(object);
}
private MongoCollection<Document> getAndPrepareCollection(MongoDatabase db, String collectionName) {
try {
@@ -2656,7 +2695,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/**
* Prepare the collection before any processing is done using it. This allows a convenient way to apply settings like
* slaveOk() etc. Can be overridden in sub-classes.
* withCodecRegistry() etc. Can be overridden in sub-classes.
*
* @param collection
*/
@@ -2720,7 +2759,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
DocumentCallback<T> objectCallback, String collectionName) {
return createMono(collectionName,
collection -> Mono.from(collectionCallback.doInCollection(collection)).map(objectCallback::doWith));
collection -> Mono.from(collectionCallback.doInCollection(collection)).flatMap(objectCallback::doWith));
}
/**
@@ -2746,7 +2785,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
return createFlux(collectionName, collection -> {
return Flux.from(preparer.initiateFind(collection, collectionCallback::doInCollection))
.map(objectCallback::doWith);
.concatMap(objectCallback::doWith);
});
}
@@ -2815,7 +2854,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 DBCollection}.
* {@link Document} and executes that against the {@link MongoCollection}.
*
* @author Oliver Gierke
* @author Thomas Risberg
@@ -2859,7 +2898,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
*
* @author Mark Paluch
*/
@RequiredArgsConstructor
private static class FindCallback implements ReactiveCollectionQueryCallback<Document> {
private final @Nullable Document query;
@@ -2869,6 +2907,12 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
this(query, null);
}
FindCallback(Document query, Document fields) {
this.query = query;
this.fields = fields;
}
@Override
public FindPublisher<Document> doInCollection(MongoCollection<Document> collection) {
@@ -2922,7 +2966,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
/**
* @author Mark Paluch
*/
@RequiredArgsConstructor
private static class FindAndModifyCallback implements ReactiveCollectionCallback<Document> {
private final Document query;
@@ -2932,6 +2975,17 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
private final List<Document> arrayFilters;
private final FindAndModifyOptions options;
FindAndModifyCallback(Document query, Document fields, Document sort, Object update, List<Document> arrayFilters,
FindAndModifyOptions options) {
this.query = query;
this.fields = fields;
this.sort = sort;
this.update = update;
this.arrayFilters = arrayFilters;
this.options = options;
}
@Override
public Publisher<Document> doInCollection(MongoCollection<Document> collection)
throws MongoException, DataAccessException {
@@ -2987,7 +3041,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* @author Christoph Strobl
* @since 2.1
*/
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
private static class FindAndReplaceCallback implements ReactiveCollectionCallback<Document> {
private final Document query;
@@ -2997,6 +3050,17 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
private final @Nullable com.mongodb.client.model.Collation collation;
private final FindAndReplaceOptions options;
FindAndReplaceCallback(Document query, Document fields, Document sort, Document update,
com.mongodb.client.model.Collation collation, FindAndReplaceOptions options) {
this.query = query;
this.fields = fields;
this.sort = sort;
this.update = update;
this.collation = collation;
this.options = options;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ReactiveCollectionCallback#doInCollection(com.mongodb.reactivestreams.client.MongoCollection)
@@ -3042,7 +3106,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
interface DocumentCallback<T> {
T doWith(Document object);
Mono<T> doWith(Document object);
}
/**
@@ -3071,6 +3135,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* {@link EntityReader}.
*
* @author Mark Paluch
* @author Roman Puchkovskiy
*/
class ReadDocumentCallback<T> implements DocumentCallback<T> {
@@ -3088,60 +3153,64 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
this.collectionName = collectionName;
}
public T doWith(@Nullable Document object) {
public Mono<T> doWith(Document document) {
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, type, collectionName));
maybeEmitEvent(new AfterLoadEvent<>(document, type, collectionName));
T source = reader.read(type, document);
if (source != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, source, collectionName));
return maybeCallAfterConvert(source, document, collectionName);
}
T source = reader.read(type, object);
if (null != source) {
maybeEmitEvent(new AfterConvertEvent<>(object, source, collectionName));
}
return source;
return Mono.empty();
}
}
/**
* {@link MongoTemplate.DocumentCallback} transforming {@link Document} into the given {@code targetType} or
* decorating the {@code sourceType} with a {@literal projection} in case the {@code targetType} is an
* {@litera interface}.
* {@link DocumentCallback} transforming {@link Document} into the given {@code targetType} or decorating the
* {@code sourceType} with a {@literal projection} in case the {@code targetType} is an {@literal interface}.
*
* @param <S>
* @param <T>
* @author Christoph Strobl
* @author Roman Puchkovskiy
* @since 2.0
*/
@RequiredArgsConstructor
private class ProjectingReadCallback<S, T> implements DocumentCallback<T> {
private final @NonNull EntityReader<Object, Bson> reader;
private final @NonNull Class<S> entityType;
private final @NonNull Class<T> targetType;
private final @NonNull String collectionName;
private final EntityReader<Object, Bson> reader;
private final Class<S> entityType;
private final Class<T> targetType;
private final String collectionName;
ProjectingReadCallback(EntityReader<Object, Bson> reader, Class<S> entityType, Class<T> targetType,
String collectionName) {
this.reader = reader;
this.entityType = entityType;
this.targetType = targetType;
this.collectionName = collectionName;
}
@Nullable
@SuppressWarnings("unchecked")
public T doWith(@Nullable Document object) {
if (object == null) {
return null;
}
public Mono<T> doWith(Document document) {
Class<?> typeToRead = targetType.isInterface() || targetType.isAssignableFrom(entityType) //
? entityType //
: targetType;
if (null != object) {
maybeEmitEvent(new AfterLoadEvent<>(object, typeToRead, collectionName));
}
maybeEmitEvent(new AfterLoadEvent<>(document, typeToRead, collectionName));
Object source = reader.read(typeToRead, object);
Object source = reader.read(typeToRead, document);
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, source) : source;
if (null != source) {
maybeEmitEvent(new AfterConvertEvent<>(object, result, collectionName));
T castEntity = (T) result;
if (castEntity != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, castEntity, collectionName));
return maybeCallAfterConvert(castEntity, document, collectionName);
}
return (T) result;
return Mono.empty();
}
}
@@ -3151,6 +3220,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
*
* @author Mark Paluch
* @author Chrstoph Strobl
* @author Roman Puchkovskiy
*/
static class GeoNearResultDocumentCallback<T> implements DocumentCallback<GeoResult<T>> {
@@ -3175,16 +3245,20 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
this.metric = metric;
}
public GeoResult<T> doWith(Document object) {
public Mono<GeoResult<T>> doWith(Document object) {
double distance = getDistance(object);
return delegate.doWith(object).map(doWith -> new GeoResult<>(doWith, new Distance(distance, metric)));
}
double getDistance(Document object) {
double distance = Double.NaN;
if (object.containsKey(distanceField)) {
distance = NumberUtils.convertNumberToTargetClass(object.get(distanceField, Number.class), Double.class);
return NumberUtils.convertNumberToTargetClass(object.get(distanceField, Number.class), Double.class);
}
T doWith = delegate.doWith(object);
return new GeoResult<>(doWith, new Distance(distance, metric));
return Double.NaN;
}
}
@@ -3202,7 +3276,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
this.type = type;
}
@SuppressWarnings("deprecation")
public FindPublisher<Document> prepare(FindPublisher<Document> findPublisher) {
FindPublisher<Document> findPublisherToUse = operations.forType(type) //
@@ -3267,7 +3340,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
@Override
public ReadPreference getReadPreference() {
return query.getMeta().getFlags().contains(CursorOption.SLAVE_OK) ? ReadPreference.primaryPreferred() : null;
return (query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS)
|| query.getMeta().getFlags().contains(CursorOption.SLAVE_OK)) ? ReadPreference.primaryPreferred() : null;
}
}
@@ -3319,7 +3393,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* @see org.springframework.data.mongodb.core.ReactiveMongoTemplate#getCollection(java.lang.String)
*/
@Override
public MongoCollection<Document> getCollection(String collectionName) {
public Mono<MongoCollection<Document>> getCollection(String collectionName) {
// native MongoDB objects that offer methods with ClientSession must not be proxied.
return delegate.getCollection(collectionName);
@@ -3330,18 +3404,21 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* @see org.springframework.data.mongodb.core.ReactiveMongoTemplate#getMongoDatabase()
*/
@Override
public MongoDatabase getMongoDatabase() {
public Mono<MongoDatabase> getMongoDatabase() {
// native MongoDB objects that offer methods with ClientSession must not be proxied.
return delegate.getMongoDatabase();
}
}
@RequiredArgsConstructor
class IndexCreatorEventListener implements ApplicationListener<MappingContextEvent<?, ?>> {
final Consumer<Throwable> subscriptionExceptionHandler;
public IndexCreatorEventListener(Consumer<Throwable> subscriptionExceptionHandler) {
this.subscriptionExceptionHandler = subscriptionExceptionHandler;
}
@Override
public void onApplicationEvent(MappingContextEvent<?, ?> event) {

View File

@@ -18,6 +18,7 @@ package org.springframework.data.mongodb.core;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import com.mongodb.client.result.DeleteResult;
@@ -106,6 +107,18 @@ public interface ReactiveRemoveOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
TerminatingRemove<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link TerminatingRemove}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default TerminatingRemove<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
interface ReactiveRemove<T> extends RemoveWithCollection<T> {}

View File

@@ -15,10 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -35,12 +31,15 @@ import com.mongodb.client.result.DeleteResult;
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
class ReactiveRemoveOperationSupport implements ReactiveRemoveOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull ReactiveMongoTemplate tempate;
private final ReactiveMongoTemplate tempate;
ReactiveRemoveOperationSupport(ReactiveMongoTemplate tempate) {
this.tempate = tempate;
}
/*
* (non-Javadoc)
@@ -54,14 +53,20 @@ class ReactiveRemoveOperationSupport implements ReactiveRemoveOperation {
return new ReactiveRemoveSupport<>(tempate, domainType, ALL_QUERY, null);
}
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ReactiveRemoveSupport<T> implements ReactiveRemove<T>, RemoveWithCollection<T> {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<T> domainType;
Query query;
String collection;
private final ReactiveMongoTemplate template;
private final Class<T> domainType;
private final Query query;
private final String collection;
ReactiveRemoveSupport(ReactiveMongoTemplate template, Class<T> domainType, Query query, String collection) {
this.template = template;
this.domainType = domainType;
this.query = query;
this.collection = collection;
}
/*
* (non-Javadoc)

View File

@@ -15,12 +15,13 @@
*/
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.aggregation.AggregationUpdate;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
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 com.mongodb.client.result.UpdateResult;
@@ -171,6 +172,18 @@ public interface ReactiveUpdateOperation {
* @throws IllegalArgumentException if query is {@literal null}.
*/
UpdateWithUpdate<T> matching(Query query);
/**
* Set the filter {@link CriteriaDefinition criteria} to be used.
*
* @param criteria must not be {@literal null}.
* @return new instance of {@link UpdateWithUpdate}.
* @throws IllegalArgumentException if query is {@literal null}.
* @since 3.0
*/
default UpdateWithUpdate<T> matching(CriteriaDefinition criteria) {
return matching(Query.query(criteria));
}
}
/**

View File

@@ -15,13 +15,10 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import reactor.core.publisher.Mono;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -35,12 +32,15 @@ import com.mongodb.client.result.UpdateResult;
* @author Christoph Strobl
* @since 2.0
*/
@RequiredArgsConstructor
class ReactiveUpdateOperationSupport implements ReactiveUpdateOperation {
private static final Query ALL_QUERY = new Query();
private final @NonNull ReactiveMongoTemplate template;
private final ReactiveMongoTemplate template;
ReactiveUpdateOperationSupport(ReactiveMongoTemplate template) {
this.template = template;
}
/*
* (non-Javadoc)
@@ -54,21 +54,34 @@ class ReactiveUpdateOperationSupport implements ReactiveUpdateOperation {
return new ReactiveUpdateSupport<>(template, domainType, ALL_QUERY, null, null, null, null, null, domainType);
}
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
static class ReactiveUpdateSupport<T>
implements ReactiveUpdate<T>, UpdateWithCollection<T>, UpdateWithQuery<T>, TerminatingUpdate<T>,
FindAndReplaceWithOptions<T>, FindAndReplaceWithProjection<T>, TerminatingFindAndReplace<T> {
@NonNull ReactiveMongoTemplate template;
@NonNull Class<?> domainType;
Query query;
org.springframework.data.mongodb.core.query.UpdateDefinition update;
@Nullable String collection;
@Nullable FindAndModifyOptions findAndModifyOptions;
@Nullable FindAndReplaceOptions findAndReplaceOptions;
@Nullable Object replacement;
@NonNull Class<T> targetType;
private final ReactiveMongoTemplate template;
private final Class<?> domainType;
private final Query query;
private final org.springframework.data.mongodb.core.query.UpdateDefinition update;
@Nullable private final String collection;
@Nullable private final FindAndModifyOptions findAndModifyOptions;
@Nullable private final FindAndReplaceOptions findAndReplaceOptions;
@Nullable private final Object replacement;
private final Class<T> targetType;
ReactiveUpdateSupport(ReactiveMongoTemplate template, Class<?> domainType, Query query, UpdateDefinition update,
String collection, FindAndModifyOptions findAndModifyOptions, FindAndReplaceOptions findAndReplaceOptions,
Object replacement, Class<T> targetType) {
this.template = template;
this.domainType = domainType;
this.query = query;
this.update = update;
this.collection = collection;
this.findAndModifyOptions = findAndModifyOptions;
this.findAndReplaceOptions = findAndReplaceOptions;
this.replacement = replacement;
this.targetType = targetType;
}
/*
* (non-Javadoc)
@@ -123,7 +136,9 @@ class ReactiveUpdateOperationSupport implements ReactiveUpdateOperation {
String collectionName = getCollectionName();
return template.findAndModify(query, update, findAndModifyOptions != null ? findAndModifyOptions : FindAndModifyOptions.none(), targetType, collectionName);
return template.findAndModify(query, update,
findAndModifyOptions != null ? findAndModifyOptions : FindAndModifyOptions.none(), targetType,
collectionName);
}
/*

View File

@@ -15,9 +15,9 @@
*/
package org.springframework.data.mongodb.core;
import lombok.Value;
import reactor.core.publisher.Mono;
import org.bson.codecs.configuration.CodecRegistry;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.dao.DataAccessException;
@@ -26,6 +26,7 @@ import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.SessionAwareMethodInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.mongodb.ClientSessionOptions;
import com.mongodb.ConnectionString;
@@ -41,6 +42,7 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.0
*/
public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, ReactiveMongoDatabaseFactory {
@@ -99,7 +101,7 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDbFactory#getMongoDatabase()
*/
public MongoDatabase getMongoDatabase() throws DataAccessException {
public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
return getMongoDatabase(databaseName);
}
@@ -107,12 +109,16 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDbFactory#getMongoDatabase(java.lang.String)
*/
public MongoDatabase getMongoDatabase(String dbName) throws DataAccessException {
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
Assert.hasText(dbName, "Database name must not be empty.");
MongoDatabase db = mongo.getDatabase(dbName);
return writeConcern != null ? db.withWriteConcern(writeConcern) : db;
return Mono.fromSupplier(() -> {
MongoDatabase db = mongo.getDatabase(dbName);
return writeConcern != null ? db.withWriteConcern(writeConcern) : db;
});
}
/**
@@ -135,6 +141,15 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
return this.exceptionTranslator;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getCodecRegistry()
*/
@Override
public CodecRegistry getCodecRegistry() {
return this.mongo.getDatabase(databaseName).getCodecRegistry();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDbFactory#getSession(com.mongodb.ClientSessionOptions)
@@ -160,19 +175,24 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
* @author Christoph Strobl
* @since 2.1
*/
@Value
static class ClientSessionBoundMongoDbFactory implements ReactiveMongoDatabaseFactory {
static final class ClientSessionBoundMongoDbFactory implements ReactiveMongoDatabaseFactory {
ClientSession session;
ReactiveMongoDatabaseFactory delegate;
private final ClientSession session;
private final ReactiveMongoDatabaseFactory delegate;
ClientSessionBoundMongoDbFactory(ClientSession session, ReactiveMongoDatabaseFactory delegate) {
this.session = session;
this.delegate = delegate;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getMongoDatabase()
*/
@Override
public MongoDatabase getMongoDatabase() throws DataAccessException {
return decorateDatabase(delegate.getMongoDatabase());
public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
return delegate.getMongoDatabase().map(this::decorateDatabase);
}
/*
@@ -180,8 +200,8 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
* @see org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getMongoDatabase(java.lang.String)
*/
@Override
public MongoDatabase getMongoDatabase(String dbName) throws DataAccessException {
return decorateDatabase(delegate.getMongoDatabase(dbName));
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return delegate.getMongoDatabase(dbName).map(this::decorateDatabase);
}
/*
@@ -193,6 +213,15 @@ public class SimpleReactiveMongoDatabaseFactory implements DisposableBean, React
return delegate.getExceptionTranslator();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getCodecRegistry()
*/
@Override
public CodecRegistry getCodecRegistry() {
return delegate.getCodecRegistry();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getSession(com.mongodb.ClientSessionOptions)
@@ -242,7 +271,42 @@ 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());
return targetType.cast(factory.getProxy(target.getClass().getClassLoader()));
}
public ClientSession getSession() {
return this.session;
}
public ReactiveMongoDatabaseFactory getDelegate() {
return this.delegate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClientSessionBoundMongoDbFactory that = (ClientSessionBoundMongoDbFactory) o;
if (!ObjectUtils.nullSafeEquals(this.session, that.session)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.delegate, that.delegate);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(this.session);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.delegate);
return result;
}
public String toString() {
return "SimpleReactiveMongoDatabaseFactory.ClientSessionBoundMongoDbFactory(session=" + this.getSession()
+ ", delegate=" + this.getDelegate() + ")";
}
}
}

View File

@@ -16,8 +16,8 @@
package org.springframework.data.mongodb.core;
/**
* 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}.
* 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}.
*
* @author Thomas Risberg
* @author Oliver Gierke

View File

@@ -17,6 +17,7 @@ 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;
@@ -28,8 +29,11 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Support class for {@link AggregationExpression} implementations.
*
* @author Christoph Strobl
* @author Matt Morrissette
* @author Mark Paluch
* @since 1.10
*/
abstract class AbstractAggregationExpression implements AggregationExpression {
@@ -48,7 +52,6 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
return toDocument(this.value, context);
}
@SuppressWarnings("unchecked")
public Document toDocument(Object value, AggregationOperationContext context) {
return new Document(getMongoMethod(), unpack(value, context));
}
@@ -100,42 +103,102 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
return value;
}
protected List<Object> append(Object value) {
@SuppressWarnings("unchecked")
protected List<Object> append(Object value, Expand expandList) {
if (this.value instanceof List) {
List<Object> clone = new ArrayList<Object>((List) this.value);
List<Object> clone = new ArrayList<>((List<Object>) this.value);
if (value instanceof List) {
clone.addAll((List) value);
if (value instanceof Collection && Expand.EXPAND_VALUES.equals(expandList)) {
clone.addAll((Collection<?>) value);
} else {
clone.add(value);
}
return clone;
}
return Arrays.asList(this.value, value);
}
@SuppressWarnings("unchecked")
protected java.util.Map<String, Object> append(String key, Object 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", "rawtypes" })
protected Map<String, Object> append(String key, Object value) {
Assert.isInstanceOf(Map.class, this.value, "Value must be a type of Map!");
java.util.Map<String, Object> clone = new LinkedHashMap<>((java.util.Map) this.value);
Map<String, Object> clone = new LinkedHashMap<>((java.util.Map) this.value);
clone.put(key, value);
return clone;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Map<String, Object> remove(String key) {
Assert.isInstanceOf(Map.class, this.value, "Value must be a type of Map!");
Map<String, Object> clone = new LinkedHashMap<>((java.util.Map) this.value);
clone.remove(key);
return clone;
}
/**
* Append the given key at the position in the underlying {@link LinkedHashMap}.
*
* @param index
* @param key
* @param value
* @return
* @since 3.1
*/
@SuppressWarnings({ "unchecked" })
protected Map<String, Object> appendAt(int index, String key, Object value) {
Assert.isInstanceOf(Map.class, this.value, "Value must be a type of Map!");
Map<String, Object> clone = new LinkedHashMap<>();
int i = 0;
for (Map.Entry<String, Object> entry : ((Map<String, Object>) this.value).entrySet()) {
if (i == index) {
clone.put(key, value);
}
if (!entry.getKey().equals(key)) {
clone.put(entry.getKey(), entry.getValue());
}
i++;
}
if (i <= index) {
clone.put(key, value);
}
return clone;
}
@SuppressWarnings({ "rawtypes" })
protected List<Object> values() {
if (value instanceof List) {
return new ArrayList<Object>((List) value);
}
if (value instanceof java.util.Map) {
return new ArrayList<Object>(((java.util.Map) value).values());
}
return new ArrayList<>(Collections.singletonList(value));
}
@@ -165,7 +228,7 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
Assert.isInstanceOf(Map.class, this.value, "Value must be a type of Map!");
return (T) ((java.util.Map<String, Object>) this.value).get(key);
return (T) ((Map<String, Object>) this.value).get(key);
}
/**
@@ -175,11 +238,11 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
* @return
*/
@SuppressWarnings("unchecked")
protected java.util.Map<String, Object> argumentMap() {
protected Map<String, Object> argumentMap() {
Assert.isInstanceOf(Map.class, this.value, "Value must be a type of Map!");
return Collections.unmodifiableMap((java.util.Map) value);
return Collections.unmodifiableMap((java.util.Map<String, Object>) value);
}
/**
@@ -196,7 +259,7 @@ abstract class AbstractAggregationExpression implements AggregationExpression {
return false;
}
return ((java.util.Map<String, Object>) this.value).containsKey(key);
return ((Map<String, Object>) this.value).containsKey(key);
}
protected abstract String getMongoMethod();

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
* @return new instance of {@link AccumulatorOperatorFactory}.
*/
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
* @return new instance of {@link AccumulatorOperatorFactory}.
*/
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
* @return new instance of {@link Sum}.
*/
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
* @return new instance of {@link Avg}.
*/
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
* @return new instance of {@link Max}.
*/
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
* @return new instance of {@link Min}.
*/
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
* @return new instance of {@link StdDevPop}.
*/
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
* @return new instance of {@link StdDevSamp}.
*/
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
* @return new instance of {@link Sum}.
*/
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
* @return new instance of {@link Sum}.
*/
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
* @return new instance of {@link Sum}.
*/
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
* @return new instance of {@link Sum}.
*/
public Sum and(AggregationExpression expression) {
@@ -264,7 +264,7 @@ public class AccumulatorOperators {
* Creates new {@link Avg}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Avg}.
*/
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
* @return new instance of {@link Avg}.
*/
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
* @return new instance of {@link Avg}.
*/
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
* @return new instance of {@link Avg}.
*/
public Avg and(AggregationExpression expression) {
@@ -347,7 +347,7 @@ public class AccumulatorOperators {
* Creates new {@link Max}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Max}.
*/
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
* @return new instance of {@link Max}.
*/
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
* @return new instance of {@link Max}.
*/
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
* @return new instance of {@link Max}.
*/
public Max and(AggregationExpression expression) {
@@ -430,7 +430,7 @@ public class AccumulatorOperators {
* Creates new {@link Min}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Min}.
*/
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
* @return new instance of {@link Min}.
*/
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
* @return new instance of {@link Min}.
*/
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
* @return new instance of {@link Min}.
*/
public Min and(AggregationExpression expression) {
@@ -513,7 +513,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevPop}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link StdDevPop}.
*/
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
* @return new instance of {@link StdDevPop}.
*/
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
* @return new instance of {@link StdDevPop}.
*/
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
* @return new instance of {@link StdDevPop}.
*/
public StdDevPop and(AggregationExpression expression) {
@@ -596,7 +596,7 @@ public class AccumulatorOperators {
* Creates new {@link StdDevSamp}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link StdDevSamp}.
*/
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
* @return new instance of {@link StdDevSamp}.
*/
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
* @return new instance of {@link StdDevSamp}.
*/
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
* @return new instance of {@link StdDevSamp}.
*/
public StdDevSamp and(AggregationExpression expression) {

View File

@@ -99,6 +99,10 @@ public class AddFieldsOperation extends DocumentEnhancingOperation {
return new AddFieldsOperationBuilder(getValueMap());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.DocumentEnhancingOperation#mongoOperator()
*/
@Override
protected String mongoOperator() {
return "$addFields";

View File

@@ -96,7 +96,7 @@ public class Aggregation {
public static final AggregationOperationContext DEFAULT_CONTEXT = AggregationOperationRenderer.DEFAULT_CONTEXT;
public static final AggregationOptions DEFAULT_OPTIONS = newAggregationOptions().build();
protected final List<AggregationOperation> operations;
protected final AggregationPipeline pipeline;
private final AggregationOptions options;
/**
@@ -133,13 +133,13 @@ public class Aggregation {
* supported in MongoDB version 2.6+.
*
* @param options must not be {@literal null}.
* @return
* @return new instance of {@link Aggregation}.
* @since 1.6
*/
public Aggregation withOptions(AggregationOptions options) {
Assert.notNull(options, "AggregationOptions must not be null.");
return new Aggregation(this.operations, options);
return new Aggregation(this.pipeline.getOperations(), options);
}
/**
@@ -202,26 +202,10 @@ public class Aggregation {
Assert.notNull(aggregationOperations, "AggregationOperations must not be null!");
Assert.notNull(options, "AggregationOptions must not be null!");
// check $out/$merge is the last operation if it exists
for (AggregationOperation aggregationOperation : aggregationOperations) {
if (aggregationOperation instanceof OutOperation && !isLast(aggregationOperation, aggregationOperations)) {
throw new IllegalArgumentException("The $out operator must be the last stage in the pipeline.");
}
if (aggregationOperation instanceof MergeOperation && !isLast(aggregationOperation, aggregationOperations)) {
throw new IllegalArgumentException("The $merge operator must be the last stage in the pipeline.");
}
}
this.operations = aggregationOperations;
this.pipeline = new AggregationPipeline(aggregationOperations);
this.options = options;
}
private boolean isLast(AggregationOperation aggregationOperation, List<AggregationOperation> aggregationOperations) {
return aggregationOperations.indexOf(aggregationOperation) == aggregationOperations.size() - 1;
}
/**
* Get the {@link AggregationOptions}.
*
@@ -259,7 +243,7 @@ public class Aggregation {
* Creates a new {@link ProjectionOperation} including the given fields.
*
* @param fields must not be {@literal null}.
* @return
* @return new instance of {@link ProjectionOperation}.
*/
public static ProjectionOperation project(String... fields) {
return project(fields(fields));
@@ -269,7 +253,7 @@ public class Aggregation {
* Creates a new {@link ProjectionOperation} including the given {@link Fields}.
*
* @param fields must not be {@literal null}.
* @return
* @return new instance of {@link ProjectionOperation}.
*/
public static ProjectionOperation project(Fields fields) {
return new ProjectionOperation(fields);
@@ -292,7 +276,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
* @return new instance of {@link UnwindOperation}.
*/
public static UnwindOperation unwind(String field) {
return new UnwindOperation(field(field));
@@ -302,7 +286,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
* @return new instance of {@link ReplaceRootOperation}.
* @since 1.10
*/
public static ReplaceRootOperation replaceRoot(String fieldName) {
@@ -314,7 +298,7 @@ public class Aggregation {
* {@link AggregationExpression}.
*
* @param aggregationExpression must not be {@literal null}.
* @return
* @return new instance of {@link ReplaceRootOperation}.
* @since 1.10
*/
public static ReplaceRootOperation replaceRoot(AggregationExpression aggregationExpression) {
@@ -380,7 +364,7 @@ public class Aggregation {
* Creates a new {@link GroupOperation} for the given fields.
*
* @param fields must not be {@literal null}.
* @return
* @return new instance of {@link GroupOperation}.
*/
public static GroupOperation group(String... fields) {
return group(fields(fields));
@@ -401,7 +385,7 @@ public class Aggregation {
* {@link GraphLookupOperation} given {@literal fromCollection}.
*
* @param fromCollection must not be {@literal null} or empty.
* @return
* @return new instance of {@link StartWithBuilder} for creating a {@link GraphLookupOperation}.
* @since 1.10
*/
public static StartWithBuilder graphLookup(String fromCollection) {
@@ -412,7 +396,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
* @return new instance of {@link SortOperation}.
*/
public static SortOperation sort(Sort sort) {
return new SortOperation(sort);
@@ -423,7 +407,7 @@ public class Aggregation {
*
* @param direction must not be {@literal null}.
* @param fields must not be {@literal null}.
* @return
* @return new instance of {@link SortOperation}.
*/
public static SortOperation sort(Direction direction, String... fields) {
return new SortOperation(Sort.by(direction, fields));
@@ -433,7 +417,7 @@ public class Aggregation {
* Creates a new {@link SortByCountOperation} given {@literal groupByField}.
*
* @param field must not be {@literal null} or empty.
* @return
* @return new instance of {@link SortByCountOperation}.
* @since 2.1
*/
public static SortByCountOperation sortByCount(String field) {
@@ -444,7 +428,7 @@ public class Aggregation {
* Creates a new {@link SortByCountOperation} given {@link AggregationExpression group and sort expression}.
*
* @param groupAndSortExpression must not be {@literal null}.
* @return
* @return new instance of {@link SortByCountOperation}.
* @since 2.1
*/
public static SortByCountOperation sortByCount(AggregationExpression groupAndSortExpression) {
@@ -455,9 +439,10 @@ public class Aggregation {
* Creates a new {@link SkipOperation} skipping the given number of elements.
*
* @param elementsToSkip must not be less than zero.
* @return
* @return new instance of {@link SkipOperation}.
* @deprecated prepare to get this one removed in favor of {@link #skip(long)}.
*/
@Deprecated
public static SkipOperation skip(int elementsToSkip) {
return new SkipOperation(elementsToSkip);
}
@@ -466,7 +451,7 @@ public class Aggregation {
* Creates a new {@link SkipOperation} skipping the given number of elements.
*
* @param elementsToSkip must not be less than zero.
* @return
* @return new instance of {@link SkipOperation}.
*/
public static SkipOperation skip(long elementsToSkip) {
return new SkipOperation(elementsToSkip);
@@ -476,7 +461,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
* @return new instance of {@link LimitOperation}.
*/
public static LimitOperation limit(long maxElements) {
return new LimitOperation(maxElements);
@@ -486,7 +471,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
* @return new instance of {@link SampleOperation}.
* @since 2.0
*/
public static SampleOperation sample(long sampleSize) {
@@ -497,7 +482,7 @@ public class Aggregation {
* Creates a new {@link MatchOperation} using the given {@link Criteria}.
*
* @param criteria must not be {@literal null}.
* @return
* @return new instance of {@link MatchOperation}.
*/
public static MatchOperation match(Criteria criteria) {
return new MatchOperation(criteria);
@@ -507,7 +492,7 @@ public class Aggregation {
* Creates a new {@link MatchOperation} using the given {@link CriteriaDefinition}.
*
* @param criteria must not be {@literal null}.
* @return
* @return new instance of {@link MatchOperation}.
* @since 1.10
*/
public static MatchOperation match(CriteriaDefinition criteria) {
@@ -520,7 +505,7 @@ public class Aggregation {
*
* @param query must not be {@literal null}.
* @param distanceField must not be {@literal null} or empty.
* @return
* @return new instance of {@link GeoNearOperation}.
* @since 1.7
*/
public static GeoNearOperation geoNear(NearQuery query, String distanceField) {
@@ -546,7 +531,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
* @return new instance of {@link OutOperation}.
*/
public static OutOperation out(String outCollectionName) {
return new OutOperation(outCollectionName);
@@ -556,7 +541,7 @@ public class Aggregation {
* Creates a new {@link BucketOperation} given {@literal groupByField}.
*
* @param groupByField must not be {@literal null} or empty.
* @return
* @return new instance of {@link BucketOperation}.
* @since 1.10
*/
public static BucketOperation bucket(String groupByField) {
@@ -567,7 +552,7 @@ public class Aggregation {
* Creates a new {@link BucketOperation} given {@link AggregationExpression group-by expression}.
*
* @param groupByExpression must not be {@literal null}.
* @return
* @return new instance of {@link BucketOperation}.
* @since 1.10
*/
public static BucketOperation bucket(AggregationExpression groupByExpression) {
@@ -579,7 +564,7 @@ public class Aggregation {
*
* @param groupByField must not be {@literal null} or empty.
* @param buckets number of buckets, must be a positive integer.
* @return
* @return new instance of {@link BucketAutoOperation}.
* @since 1.10
*/
public static BucketAutoOperation bucketAuto(String groupByField, int buckets) {
@@ -591,7 +576,7 @@ public class Aggregation {
*
* @param groupByExpression must not be {@literal null}.
* @param buckets number of buckets, must be a positive integer.
* @return
* @return new instance of {@link BucketAutoOperation}.
* @since 1.10
*/
public static BucketAutoOperation bucketAuto(AggregationExpression groupByExpression, int buckets) {
@@ -601,7 +586,7 @@ public class Aggregation {
/**
* Creates a new {@link FacetOperation}.
*
* @return
* @return new instance of {@link FacetOperation}.
* @since 1.10
*/
public static FacetOperation facet() {
@@ -612,7 +597,7 @@ public class Aggregation {
* Creates a new {@link FacetOperationBuilder} given {@link Aggregation}.
*
* @param aggregationOperations the sub-pipeline, must not be {@literal null}.
* @return
* @return new instance of {@link FacetOperation}.
* @since 1.10
*/
public static FacetOperationBuilder facet(AggregationOperation... aggregationOperations) {
@@ -657,11 +642,31 @@ public class Aggregation {
return new CountOperationBuilder();
}
/**
* Creates a new {@link RedactOperation} that can restrict the content of a document based on information stored
* within the document itself.
*
* <pre class="code">
*
* Aggregation.redact(ConditionalOperators.when(Criteria.where("level").is(5)) //
* .then(RedactOperation.PRUNE) //
* .otherwise(RedactOperation.DESCEND));
* </pre>
*
* @param condition Any {@link AggregationExpression} that resolves to {@literal $$DESCEND}, {@literal $$PRUNE}, or
* {@literal $$KEEP}. Must not be {@literal null}.
* @return new instance of {@link RedactOperation}. Never {@literal null}.
* @since 3.0
*/
public static RedactOperation redact(AggregationExpression condition) {
return new RedactOperation(condition);
}
/**
* Creates a new {@link Fields} instance for the given field names.
*
* @param fields must not be {@literal null}.
* @return
* @return new instance of {@link Fields}.
* @see Fields#fields(String...)
*/
public static Fields fields(String... fields) {
@@ -673,7 +678,7 @@ public class Aggregation {
*
* @param name must not be {@literal null} or empty.
* @param target must not be {@literal null} or empty.
* @return
* @return new instance of {@link Fields}.
*/
public static Fields bind(String name, String target) {
return Fields.from(field(name, target));
@@ -682,7 +687,7 @@ public class Aggregation {
/**
* Returns a new {@link AggregationOptions.Builder}.
*
* @return
* @return new instance of {@link AggregationOptions.Builder}.
* @since 1.6
*/
public static AggregationOptions.Builder newAggregationOptions() {
@@ -697,7 +702,15 @@ public class Aggregation {
* @since 2.1
*/
public List<Document> toPipeline(AggregationOperationContext rootContext) {
return AggregationOperationRenderer.toDocument(operations, rootContext);
return pipeline.toDocuments(rootContext);
}
/**
* @return the {@link AggregationPipeline}.
* @since 3.0.2
*/
public AggregationPipeline getPipeline() {
return pipeline;
}
/**
@@ -744,7 +757,7 @@ public class Aggregation {
* otherwise.
*
* @param fieldRef may be {@literal null}.
* @return
* @return {@literal true} if the given field refers to a {@link SystemVariable}.
*/
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
* @return
* @param context must not be {@literal null}.
* @return the MongoDB native ({@link Document}) form of the expression.
*/
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 aggregationContext must not be {@literal null}.
* @param context 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
* @return never {@literal null}.
*/
public AggregationOperationContext getAggregationContext() {
return aggregationContext;
@@ -76,7 +76,7 @@ interface AggregationExpressionTransformer
/**
* Returns the {@link FieldReference} for the current {@link ExpressionNode}.
*
* @return
* @return never {@literal null}.
*/
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
* @return new instance of {@link AggregationExpression}.
*/
public AggregationExpression of(Object... parameters) {

View File

@@ -54,4 +54,15 @@ public interface AggregationOperation {
default List<Document> toPipelineStages(AggregationOperationContext context) {
return Collections.singletonList(toDocument(context));
}
/**
* Return the MongoDB operator that is used for this {@link AggregationOperation}. Aggregation operations should
* implement this method to avoid document rendering.
*
* @return the operator used for this {@link AggregationOperation}.
* @since 3.0.2
*/
default String getOperator() {
return toDocument(Aggregation.DEFAULT_CONTEXT).keySet().iterator().next();
}
}

View File

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

View File

@@ -32,6 +32,7 @@ import org.springframework.util.Assert;
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @author Yadhukrishna S Pai
* @see Aggregation#withOptions(AggregationOptions)
* @see TypedAggregation#withOptions(AggregationOptions)
* @since 1.6
@@ -45,13 +46,16 @@ public class AggregationOptions {
private static final String COLLATION = "collation";
private static final String COMMENT = "comment";
private static final String MAX_TIME = "maxTimeMS";
private static final String HINT = "hint";
private final boolean allowDiskUse;
private final boolean explain;
private final Optional<Document> cursor;
private final Optional<Collation> collation;
private final Optional<String> comment;
private final Optional<Document> hint;
private Duration maxTime = Duration.ZERO;
private ResultOptions resultOptions = ResultOptions.READ;
/**
* Creates a new {@link AggregationOptions}.
@@ -76,7 +80,7 @@ public class AggregationOptions {
*/
public AggregationOptions(boolean allowDiskUse, boolean explain, @Nullable Document cursor,
@Nullable Collation collation) {
this(allowDiskUse, explain, cursor, collation, null);
this(allowDiskUse, explain, cursor, collation, null, null);
}
/**
@@ -92,12 +96,30 @@ public class AggregationOptions {
*/
public AggregationOptions(boolean allowDiskUse, boolean explain, @Nullable Document cursor,
@Nullable Collation collation, @Nullable String comment) {
this(allowDiskUse, explain, cursor, collation, comment, null);
}
/**
* Creates a new {@link AggregationOptions}.
*
* @param allowDiskUse whether to off-load intensive sort-operations to disk.
* @param explain whether to get the execution plan for the aggregation instead of the actual results.
* @param cursor can be {@literal null}, used to pass additional options (such as {@code batchSize}) to the
* aggregation.
* @param collation collation for string comparison. Can be {@literal null}.
* @param comment execution comment. Can be {@literal null}.
* @param hint can be {@literal null}, used to provide an index that would be forcibly used by query optimizer.
* @since 3.1
*/
private AggregationOptions(boolean allowDiskUse, boolean explain, @Nullable Document cursor,
@Nullable Collation collation, @Nullable String comment, @Nullable Document hint) {
this.allowDiskUse = allowDiskUse;
this.explain = explain;
this.cursor = Optional.ofNullable(cursor);
this.collation = Optional.ofNullable(collation);
this.comment = Optional.ofNullable(comment);
this.hint = Optional.ofNullable(hint);
}
/**
@@ -129,8 +151,9 @@ public class AggregationOptions {
Collation collation = document.containsKey(COLLATION) ? Collation.from(document.get(COLLATION, Document.class))
: null;
String comment = document.getString(COMMENT);
Document hint = document.get(HINT, Document.class);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment, hint);
if (document.containsKey(MAX_TIME)) {
options.maxTime = Duration.ofMillis(document.getLong(MAX_TIME));
}
@@ -151,7 +174,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
* @return {@literal true} if enabled.
*/
public boolean isAllowDiskUse() {
return allowDiskUse;
@@ -160,7 +183,7 @@ public class AggregationOptions {
/**
* Specifies to return the information on the processing of the pipeline.
*
* @return
* @return {@literal true} if enabled.
*/
public boolean isExplain() {
return explain;
@@ -185,7 +208,7 @@ public class AggregationOptions {
/**
* Specify a document that contains options that control the creation of the cursor object.
*
* @return
* @return never {@literal null}.
*/
public Optional<Document> getCursor() {
return cursor;
@@ -194,7 +217,7 @@ public class AggregationOptions {
/**
* Get collation settings for string comparison.
*
* @return
* @return never {@literal null}.
* @since 2.0
*/
public Optional<Collation> getCollation() {
@@ -204,13 +227,23 @@ public class AggregationOptions {
/**
* Get the comment for the aggregation.
*
* @return
* @return never {@literal null}.
* @since 2.2
*/
public Optional<String> getComment() {
return comment;
}
/**
* Get the hint used to to fulfill the aggregation.
*
* @return never {@literal null}.
* @since 3.1
*/
public Optional<Document> getHint() {
return hint;
}
/**
* @return the time limit for processing. {@link Duration#ZERO} is used for the default unbounded behavior.
* @since 3.0
@@ -219,6 +252,15 @@ public class AggregationOptions {
return maxTime;
}
/**
* @return {@literal true} to skip results when running an aggregation. Useful in combination with {@code $merge} or
* {@code $out}.
* @since 3.0.2
*/
public boolean isSkipResults() {
return ResultOptions.SKIP.equals(resultOptions);
}
/**
* Returns a new potentially adjusted copy for the given {@code aggregationCommandObject} with the configuration
* applied.
@@ -238,6 +280,10 @@ public class AggregationOptions {
result.put(EXPLAIN, explain);
}
if (result.containsKey(HINT)) {
hint.ifPresent(val -> result.append(HINT, val));
}
if (!result.containsKey(CURSOR)) {
cursor.ifPresent(val -> result.put(CURSOR, val));
}
@@ -256,7 +302,7 @@ public class AggregationOptions {
/**
* Returns a {@link Document} representation of this {@link AggregationOptions}.
*
* @return
* @return never {@literal null}.
*/
public Document toDocument() {
@@ -267,6 +313,7 @@ public class AggregationOptions {
cursor.ifPresent(val -> document.put(CURSOR, val));
collation.ifPresent(val -> document.append(COLLATION, val.toDocument()));
comment.ifPresent(val -> document.append(COMMENT, val));
hint.ifPresent(val -> document.append(HINT, val));
if (hasExecutionTimeLimit()) {
document.append(MAX_TIME, maxTime.toMillis());
@@ -276,7 +323,7 @@ public class AggregationOptions {
}
/**
* @return
* @return {@literal true} if {@link #maxTime} is set to a positive value.
* @since 3.0
*/
public boolean hasExecutionTimeLimit() {
@@ -308,13 +355,15 @@ public class AggregationOptions {
private @Nullable Document cursor;
private @Nullable Collation collation;
private @Nullable String comment;
private @Nullable Document hint;
private @Nullable Duration maxTime;
private @Nullable ResultOptions resultOptions;
/**
* Defines whether to off-load intensive sort-operations to disk.
*
* @param allowDiskUse
* @return
* @param allowDiskUse use {@literal true} to allow disk use during the aggregation.
* @return this.
*/
public Builder allowDiskUse(boolean allowDiskUse) {
@@ -325,8 +374,8 @@ public class AggregationOptions {
/**
* Defines whether to get the execution plan for the aggregation instead of the actual results.
*
* @param explain
* @return
* @param explain use {@literal true} to enable explain feature.
* @return this.
*/
public Builder explain(boolean explain) {
@@ -337,8 +386,8 @@ public class AggregationOptions {
/**
* Additional options to the aggregation.
*
* @param cursor
* @return
* @param cursor must not be {@literal null}.
* @return this.
*/
public Builder cursor(Document cursor) {
@@ -349,8 +398,8 @@ public class AggregationOptions {
/**
* Define the initial cursor batch size.
*
* @param batchSize
* @return
* @param batchSize use a positive int.
* @return this.
* @since 2.0
*/
public Builder cursorBatchSize(int batchSize) {
@@ -363,7 +412,7 @@ public class AggregationOptions {
* Define collation settings for string comparison.
*
* @param collation can be {@literal null}.
* @return
* @return this.
* @since 2.0
*/
public Builder collation(@Nullable Collation collation) {
@@ -376,7 +425,7 @@ public class AggregationOptions {
* Define a comment to describe the execution.
*
* @param comment can be {@literal null}.
* @return
* @return this.
* @since 2.2
*/
public Builder comment(@Nullable String comment) {
@@ -385,6 +434,19 @@ public class AggregationOptions {
return this;
}
/**
* Define a hint that is used by query optimizer to to fulfill the aggregation.
*
* @param hint can be {@literal null}.
* @return this.
* @since 3.1
*/
public Builder hint(@Nullable Document hint) {
this.hint = hint;
return this;
}
/**
* Set the time limit for processing.
*
@@ -399,19 +461,51 @@ public class AggregationOptions {
return this;
}
/**
* Run the aggregation, but do NOT read the aggregation result from the store. <br />
* If the expected result of the aggregation is rather large, eg. when using an {@literal $out} operation, this
* option allows to execute the aggregation without having the cursor return the operation result.
*
* @return this.
* @since 3.0.2
*/
public Builder skipOutput() {
this.resultOptions = ResultOptions.SKIP;
return this;
}
/**
* Returns a new {@link AggregationOptions} instance with the given configuration.
*
* @return
* @return new instance of {@link AggregationOptions}.
*/
public AggregationOptions build() {
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment);
AggregationOptions options = new AggregationOptions(allowDiskUse, explain, cursor, collation, comment, hint);
if (maxTime != null) {
options.maxTime = maxTime;
}
if (resultOptions != null) {
options.resultOptions = resultOptions;
}
return options;
}
}
/**
* @since 3.0
*/
private enum ResultOptions {
/**
* Just do it!, and do not read the operation result.
*/
SKIP,
/**
* Read the aggregation result from the cursor.
*/
READ;
}
}

View File

@@ -0,0 +1,162 @@
/*
* Copyright 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.Collections;
import java.util.List;
import java.util.function.Predicate;
import org.bson.Document;
import org.springframework.util.Assert;
/**
* The {@link AggregationPipeline} holds the collection of {@link AggregationOperation aggregation stages}.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 3.0.2
*/
public class AggregationPipeline {
private final List<AggregationOperation> pipeline;
/**
* Create an empty pipeline
*/
public AggregationPipeline() {
this(new ArrayList<>());
}
/**
* Create a new pipeline with given {@link AggregationOperation stages}.
*
* @param aggregationOperations must not be {@literal null}.
*/
public AggregationPipeline(List<AggregationOperation> aggregationOperations) {
Assert.notNull(aggregationOperations, "AggregationOperations must not be null!");
pipeline = new ArrayList<>(aggregationOperations);
}
/**
* Append the given {@link AggregationOperation stage} to the pipeline.
*
* @param aggregationOperation must not be {@literal null}.
* @return this.
*/
public AggregationPipeline add(AggregationOperation aggregationOperation) {
Assert.notNull(aggregationOperation, "AggregationOperation must not be null!");
pipeline.add(aggregationOperation);
return this;
}
/**
* Get the list of {@link AggregationOperation aggregation stages}.
*
* @return never {@literal null}.
*/
public List<AggregationOperation> getOperations() {
return Collections.unmodifiableList(pipeline);
}
List<Document> toDocuments(AggregationOperationContext context) {
verify();
return AggregationOperationRenderer.toDocument(pipeline, context);
}
/**
* @return {@literal true} if the last aggregation stage is either {@literal $out} or {@literal $merge}.
*/
public boolean isOutOrMerge() {
if (isEmpty()) {
return false;
}
AggregationOperation operation = pipeline.get(pipeline.size() - 1);
return isOut(operation) || isMerge(operation);
}
void verify() {
// check $out/$merge is the last operation if it exists
for (AggregationOperation operation : pipeline) {
if (isOut(operation) && !isLast(operation)) {
throw new IllegalArgumentException("The $out operator must be the last stage in the pipeline.");
}
if (isMerge(operation) && !isLast(operation)) {
throw new IllegalArgumentException("The $merge operator must be the last stage in the pipeline.");
}
}
}
/**
* Return whether this aggregation pipeline defines a {@code $unionWith} stage that may contribute documents from
* other collections. Checking for presence of union stages is useful when attempting to determine the aggregation
* element type for mapping metadata computation.
*
* @return {@literal true} the aggregation pipeline makes use of {@code $unionWith}.
* @since 3.1
*/
public boolean containsUnionWith() {
return containsOperation(AggregationPipeline::isUnionWith);
}
/**
* @return {@literal true} if the pipeline does not contain any stages.
* @since 3.1
*/
public boolean isEmpty() {
return pipeline.isEmpty();
}
private boolean containsOperation(Predicate<AggregationOperation> predicate) {
if (isEmpty()) {
return false;
}
for (AggregationOperation element : pipeline) {
if (predicate.test(element)) {
return true;
}
}
return false;
}
private boolean isLast(AggregationOperation aggregationOperation) {
return pipeline.indexOf(aggregationOperation) == pipeline.size() - 1;
}
private static boolean isUnionWith(AggregationOperation operator) {
return operator instanceof UnionWithOperation || operator.getOperator().equals("$unionWith");
}
private static boolean isMerge(AggregationOperation operator) {
return operator instanceof MergeOperation || operator.getOperator().equals("$merge");
}
private static boolean isOut(AggregationOperation operator) {
return operator instanceof OutOperation || operator.getOperator().equals("$out");
}
}

View File

@@ -59,7 +59,7 @@ public class AggregationResults<T> implements Iterable<T> {
/**
* Returns the aggregation results.
*
* @return
* @return the list of already mapped results or an empty one if none found.
*/
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
* @return the single already mapped result object or raise an error if more than one found.
* @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
* @return can be {@literal null}.
*/
@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
* @return the raw response.
* @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
* @return new instance of {@link AggregationSpELExpression}.
*/
public static AggregationSpELExpression expressionOf(String expressionString, Object... parameters) {

View File

@@ -139,7 +139,7 @@ public class AggregationUpdate extends Aggregation implements UpdateDefinition {
setOperation.getFields().forEach(it -> {
keysTouched.add(it.getName());
});
operations.add(setOperation);
pipeline.add(setOperation);
return this;
}
@@ -155,7 +155,7 @@ public class AggregationUpdate extends Aggregation implements UpdateDefinition {
Assert.notNull(unsetOperation, "UnsetOperation must not be null!");
operations.add(unsetOperation);
pipeline.add(unsetOperation);
keysTouched.addAll(unsetOperation.removedFieldNames());
return this;
}
@@ -164,7 +164,7 @@ public class AggregationUpdate extends Aggregation implements UpdateDefinition {
* {@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
* @param replaceWithOperation must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/replaceWith/">$replaceWith Aggregation
* Reference</a>
@@ -172,7 +172,7 @@ public class AggregationUpdate extends Aggregation implements UpdateDefinition {
public AggregationUpdate replaceWith(ReplaceWithOperation replaceWithOperation) {
Assert.notNull(replaceWithOperation, "ReplaceWithOperation must not be null!");
operations.add(replaceWithOperation);
pipeline.add(replaceWithOperation);
return this;
}
@@ -219,8 +219,8 @@ public class AggregationUpdate extends Aggregation implements UpdateDefinition {
/**
* Short for {@link #unset(UnsetOperation)}.
*
* @param keys
* @return
* @param keys the fields to remove.
* @return this.
*/
public AggregationUpdate unset(String... keys) {

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
* @return never {@literal null}.
*/
public static List<Long> toRangeValues(Range<Long> range) {
static List<Long> toRangeValues(Range<Long> range) {
Assert.notNull(range, "Range must not be null!");

View File

@@ -38,7 +38,7 @@ public class ArithmeticOperators {
* Take the field referenced by given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ArithmeticOperatorFactory}.
*/
public static ArithmeticOperatorFactory valueOf(String fieldReference) {
return new ArithmeticOperatorFactory(fieldReference);
@@ -48,7 +48,7 @@ public class ArithmeticOperators {
* Take the value resulting from the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link ArithmeticOperatorFactory}.
*/
public static ArithmeticOperatorFactory valueOf(AggregationExpression expression) {
return new ArithmeticOperatorFactory(expression);
@@ -89,7 +89,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that returns the absolute value of the associated number.
*
* @return
* @return new instance of {@link Abs}.
*/
public Abs abs() {
return usesFieldRef() ? Abs.absoluteValueOf(fieldReference) : Abs.absoluteValueOf(expression);
@@ -100,7 +100,7 @@ public class ArithmeticOperators {
* number.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public Add add(String fieldReference) {
@@ -113,7 +113,7 @@ public class ArithmeticOperators {
* {@link AggregationExpression} to the associated number.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public Add add(AggregationExpression expression) {
@@ -125,7 +125,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that adds the given {@literal value} to the associated number.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public Add add(Number value) {
@@ -141,7 +141,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that returns the smallest integer greater than or equal to the
* assoicated number.
*
* @return
* @return new instance of {@link Ceil}.
*/
public Ceil ceil() {
return usesFieldRef() ? Ceil.ceilValueOf(fieldReference) : Ceil.ceilValueOf(expression);
@@ -152,7 +152,7 @@ public class ArithmeticOperators {
* {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Divide}.
*/
public Divide divideBy(String fieldReference) {
@@ -165,7 +165,7 @@ public class ArithmeticOperators {
* {@literal expression}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Divide}.
*/
public Divide divideBy(AggregationExpression expression) {
@@ -176,8 +176,8 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that divides the associated number by given {@literal value}.
*
* @param value
* @return
* @param value must not be {@literal null}.
* @return new instance of {@link Divide}.
*/
public Divide divideBy(Number value) {
@@ -192,7 +192,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that raises Eulers number (i.e. e ) on the associated number.
*
* @return
* @return new instance of {@link Exp}.
*/
public Exp exp() {
return usesFieldRef() ? Exp.expValueOf(fieldReference) : Exp.expValueOf(expression);
@@ -202,7 +202,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that returns the largest integer less than or equal to the associated
* number.
*
* @return
* @return new instance of {@link Floor}.
*/
public Floor floor() {
return usesFieldRef() ? Floor.floorValueOf(fieldReference) : Floor.floorValueOf(expression);
@@ -212,7 +212,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that calculates the natural logarithm ln (i.e loge) of the assoicated
* number.
*
* @return
* @return new instance of {@link Ln}.
*/
public Ln ln() {
return usesFieldRef() ? Ln.lnValueOf(fieldReference) : Ln.lnValueOf(expression);
@@ -223,7 +223,7 @@ public class ArithmeticOperators {
* referenced via {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Log}.
*/
public Log log(String fieldReference) {
@@ -236,7 +236,7 @@ public class ArithmeticOperators {
* extracted by given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Log}.
*/
public Log log(AggregationExpression expression) {
@@ -249,7 +249,7 @@ public class ArithmeticOperators {
* {@literal base}.
*
* @param base must not be {@literal null}.
* @return
* @return new instance of {@link Log}.
*/
public Log log(Number base) {
@@ -264,7 +264,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that calculates the log base 10 for the associated number.
*
* @return
* @return new instance of {@link Log10}.
*/
public Log10 log10() {
return usesFieldRef() ? Log10.log10ValueOf(fieldReference) : Log10.log10ValueOf(expression);
@@ -275,7 +275,7 @@ public class ArithmeticOperators {
* remainder.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public Mod mod(String fieldReference) {
@@ -288,7 +288,7 @@ public class ArithmeticOperators {
* remainder.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public Mod mod(AggregationExpression expression) {
@@ -301,7 +301,7 @@ public class ArithmeticOperators {
* remainder.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public Mod mod(Number value) {
@@ -317,7 +317,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that multiplies the associated number with another.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(String fieldReference) {
@@ -329,7 +329,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that multiplies the associated number with another.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(AggregationExpression expression) {
@@ -341,7 +341,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that multiplies the associated number with another.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(Number value) {
@@ -357,7 +357,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that raises the associated number to the specified exponent.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Pow}.
*/
public Pow pow(String fieldReference) {
@@ -369,7 +369,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that raises the associated number to the specified exponent.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Pow}.
*/
public Pow pow(AggregationExpression expression) {
@@ -381,7 +381,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that raises the associated number to the specified exponent.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Pow}.
*/
public Pow pow(Number value) {
@@ -396,7 +396,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that calculates the square root of the associated number.
*
* @return
* @return new instance of {@link Sqrt}.
*/
public Sqrt sqrt() {
return usesFieldRef() ? Sqrt.sqrtOf(fieldReference) : Sqrt.sqrtOf(expression);
@@ -406,7 +406,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that subtracts value of given from the associated number.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Subtract}.
*/
public Subtract subtract(String fieldReference) {
@@ -418,7 +418,7 @@ public class ArithmeticOperators {
* Creates new {@link AggregationExpression} that subtracts value of given from the associated number.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Subtract}.
*/
public Subtract subtract(AggregationExpression expression) {
@@ -429,8 +429,8 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that subtracts value from the associated number.
*
* @param value
* @return
* @param value must not be {@literal null}.
* @return new instance of {@link Subtract}.
*/
public Subtract subtract(Number value) {
@@ -445,7 +445,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that truncates a number to its integer.
*
* @return
* @return new instance of {@link Trunc}.
*/
public Trunc trunc() {
return usesFieldRef() ? Trunc.truncValueOf(fieldReference) : Trunc.truncValueOf(expression);
@@ -454,7 +454,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that calculates and returns the sum of numeric values.
*
* @return
* @return new instance of {@link Sum}.
*/
public Sum sum() {
return usesFieldRef() ? AccumulatorOperators.Sum.sumOf(fieldReference)
@@ -464,7 +464,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that returns the average value of the numeric values.
*
* @return
* @return new instance of {@link Avg}.
*/
public Avg avg() {
return usesFieldRef() ? AccumulatorOperators.Avg.avgOf(fieldReference)
@@ -474,7 +474,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that returns the maximum value.
*
* @return
* @return new instance of {@link Max}.
*/
public Max max() {
return usesFieldRef() ? AccumulatorOperators.Max.maxOf(fieldReference)
@@ -484,7 +484,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that returns the minimum value.
*
* @return
* @return new instance of {@link Min}.
*/
public Min min() {
return usesFieldRef() ? AccumulatorOperators.Min.minOf(fieldReference)
@@ -494,7 +494,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that calculates the population standard deviation of the input values.
*
* @return
* @return new instance of {@link StdDevPop}.
*/
public StdDevPop stdDevPop() {
return usesFieldRef() ? AccumulatorOperators.StdDevPop.stdDevPopOf(fieldReference)
@@ -504,7 +504,7 @@ public class ArithmeticOperators {
/**
* Creates new {@link AggregationExpression} that calculates the sample standard deviation of the input values.
*
* @return
* @return new instance of {@link StdDevSamp}.
*/
public StdDevSamp stdDevSamp() {
return usesFieldRef() ? AccumulatorOperators.StdDevSamp.stdDevSampOf(fieldReference)
@@ -557,7 +557,7 @@ public class ArithmeticOperators {
* Creates new {@link Abs}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Abs}.
*/
public static Abs absoluteValueOf(String fieldReference) {
@@ -569,7 +569,7 @@ public class ArithmeticOperators {
* Creates new {@link Abs}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Abs}.
*/
public static Abs absoluteValueOf(AggregationExpression expression) {
@@ -581,7 +581,7 @@ public class ArithmeticOperators {
* Creates new {@link Abs}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Abs}.
*/
public static Abs absoluteValueOf(Number value) {
@@ -610,7 +610,7 @@ public class ArithmeticOperators {
* Creates new {@link Add}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public static Add valueOf(String fieldReference) {
@@ -622,7 +622,7 @@ public class ArithmeticOperators {
* Creates new {@link Add}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public static Add valueOf(AggregationExpression expression) {
@@ -634,7 +634,7 @@ public class ArithmeticOperators {
* Creates new {@link Add}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Add}.
*/
public static Add valueOf(Number value) {
@@ -642,18 +642,36 @@ public class ArithmeticOperators {
return new Add(Collections.singletonList(value));
}
/**
* Add the value stored at the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Add}.
*/
public Add add(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Add(append(Fields.field(fieldReference)));
}
/**
* Add the evaluation result of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Add}.
*/
public Add add(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Add(append(expression));
}
/**
* Add the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Add}.
*/
public Add add(Number value) {
return new Add(append(value));
}
@@ -679,7 +697,7 @@ public class ArithmeticOperators {
* Creates new {@link Ceil}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Ceil}.
*/
public static Ceil ceilValueOf(String fieldReference) {
@@ -691,7 +709,7 @@ public class ArithmeticOperators {
* Creates new {@link Ceil}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Ceil}.
*/
public static Ceil ceilValueOf(AggregationExpression expression) {
@@ -703,7 +721,7 @@ public class ArithmeticOperators {
* Creates new {@link Ceil}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Ceil}.
*/
public static Ceil ceilValueOf(Number value) {
@@ -732,7 +750,7 @@ public class ArithmeticOperators {
* Creates new {@link Divide}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Divide}.
*/
public static Divide valueOf(String fieldReference) {
@@ -744,7 +762,7 @@ public class ArithmeticOperators {
* Creates new {@link Divide}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Divide}.
*/
public static Divide valueOf(AggregationExpression expression) {
@@ -756,7 +774,7 @@ public class ArithmeticOperators {
* Creates new {@link Divide}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Divide}.
*/
public static Divide valueOf(Number value) {
@@ -764,18 +782,36 @@ public class ArithmeticOperators {
return new Divide(Collections.singletonList(value));
}
/**
* Divide by the value stored at the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Divide}.
*/
public Divide divideBy(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Divide(append(Fields.field(fieldReference)));
}
/**
* Divide by the evaluation results of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Divide}.
*/
public Divide divideBy(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Divide(append(expression));
}
/**
* Divide by the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Divide}.
*/
public Divide divideBy(Number value) {
return new Divide(append(value));
}
@@ -801,7 +837,7 @@ public class ArithmeticOperators {
* Creates new {@link Exp}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Exp}.
*/
public static Exp expValueOf(String fieldReference) {
@@ -813,7 +849,7 @@ public class ArithmeticOperators {
* Creates new {@link Exp}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Exp}.
*/
public static Exp expValueOf(AggregationExpression expression) {
@@ -825,7 +861,7 @@ public class ArithmeticOperators {
* Creates new {@link Exp}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Exp}.
*/
public static Exp expValueOf(Number value) {
@@ -854,7 +890,7 @@ public class ArithmeticOperators {
* Creates new {@link Floor}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Floor}.
*/
public static Floor floorValueOf(String fieldReference) {
@@ -866,7 +902,7 @@ public class ArithmeticOperators {
* Creates new {@link Floor}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Floor}.
*/
public static Floor floorValueOf(AggregationExpression expression) {
@@ -878,7 +914,7 @@ public class ArithmeticOperators {
* Creates new {@link Floor}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Floor}.
*/
public static Floor floorValueOf(Number value) {
@@ -907,7 +943,7 @@ public class ArithmeticOperators {
* Creates new {@link Ln}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Ln}.
*/
public static Ln lnValueOf(String fieldReference) {
@@ -919,7 +955,7 @@ public class ArithmeticOperators {
* Creates new {@link Ln}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Ln}.
*/
public static Ln lnValueOf(AggregationExpression expression) {
@@ -931,7 +967,7 @@ public class ArithmeticOperators {
* Creates new {@link Ln}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Ln}.
*/
public static Ln lnValueOf(Number value) {
@@ -960,7 +996,7 @@ public class ArithmeticOperators {
* Creates new {@link Min}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Log}.
*/
public static Log valueOf(String fieldReference) {
@@ -972,7 +1008,7 @@ public class ArithmeticOperators {
* Creates new {@link Log}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Log}.
*/
public static Log valueOf(AggregationExpression expression) {
@@ -992,18 +1028,36 @@ public class ArithmeticOperators {
return new Log(Collections.singletonList(value));
}
/**
* Use the value stored at the given field as log base.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Log}.
*/
public Log log(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Log(append(Fields.field(fieldReference)));
}
/**
* Use the evaluated value of the given {@link AggregationExpression} as log base.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Log}.
*/
public Log log(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Log(append(expression));
}
/**
* Use the given value as log base.
*
* @param base must not be {@literal null}.
* @return new instance of {@link Log}.
*/
public Log log(Number base) {
return new Log(append(base));
}
@@ -1029,7 +1083,7 @@ public class ArithmeticOperators {
* Creates new {@link Log10}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Log10}.
*/
public static Log10 log10ValueOf(String fieldReference) {
@@ -1041,7 +1095,7 @@ public class ArithmeticOperators {
* Creates new {@link Log10}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Log10}.
*/
public static Log10 log10ValueOf(AggregationExpression expression) {
@@ -1053,7 +1107,7 @@ public class ArithmeticOperators {
* Creates new {@link Log10}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Log10}.
*/
public static Log10 log10ValueOf(Number value) {
@@ -1082,7 +1136,7 @@ public class ArithmeticOperators {
* Creates new {@link Mod}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public static Mod valueOf(String fieldReference) {
@@ -1094,7 +1148,7 @@ public class ArithmeticOperators {
* Creates new {@link Mod}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public static Mod valueOf(AggregationExpression expression) {
@@ -1106,7 +1160,7 @@ public class ArithmeticOperators {
* Creates new {@link Mod}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Mod}.
*/
public static Mod valueOf(Number value) {
@@ -1114,18 +1168,36 @@ public class ArithmeticOperators {
return new Mod(Collections.singletonList(value));
}
/**
* Use the value stored at the given field as mod base.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Mod}.
*/
public Mod mod(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Mod(append(Fields.field(fieldReference)));
}
/**
* Use evaluated value of the given {@link AggregationExpression} as mod base.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Mod}.
*/
public Mod mod(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Mod(append(expression));
}
/**
* Use the given value as mod base.
*
* @param base must not be {@literal null}.
* @return new instance of {@link Mod}.
*/
public Mod mod(Number base) {
return new Mod(append(base));
}
@@ -1151,7 +1223,7 @@ public class ArithmeticOperators {
* Creates new {@link Multiply}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public static Multiply valueOf(String fieldReference) {
@@ -1163,7 +1235,7 @@ public class ArithmeticOperators {
* Creates new {@link Multiply}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public static Multiply valueOf(AggregationExpression expression) {
@@ -1175,7 +1247,7 @@ public class ArithmeticOperators {
* Creates new {@link Multiply}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Multiply}.
*/
public static Multiply valueOf(Number value) {
@@ -1183,18 +1255,36 @@ public class ArithmeticOperators {
return new Multiply(Collections.singletonList(value));
}
/**
* Multiply by the value stored at the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Multiply(append(Fields.field(fieldReference)));
}
/**
* Multiply by the evaluated value of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Multiply(append(expression));
}
/**
* Multiply by the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Multiply}.
*/
public Multiply multiplyBy(Number value) {
return new Multiply(append(value));
}
@@ -1252,18 +1342,36 @@ public class ArithmeticOperators {
return new Pow(Collections.singletonList(value));
}
/**
* Pow by the value stored at the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Pow pow(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Pow(append(Fields.field(fieldReference)));
}
/**
* Pow by the evaluated value of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Pow pow(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Pow(append(expression));
}
/**
* Pow by the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Pow pow(Number value) {
return new Pow(append(value));
}
@@ -1289,7 +1397,7 @@ public class ArithmeticOperators {
* Creates new {@link Sqrt}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Sqrt}.
*/
public static Sqrt sqrtOf(String fieldReference) {
@@ -1301,7 +1409,7 @@ public class ArithmeticOperators {
* Creates new {@link Sqrt}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Sqrt}.
*/
public static Sqrt sqrtOf(AggregationExpression expression) {
@@ -1313,7 +1421,7 @@ public class ArithmeticOperators {
* Creates new {@link Sqrt}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Sqrt}.
*/
public static Sqrt sqrtOf(Number value) {
@@ -1342,7 +1450,7 @@ public class ArithmeticOperators {
* Creates new {@link Subtract}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Subtract}.
*/
public static Subtract valueOf(String fieldReference) {
@@ -1354,7 +1462,7 @@ public class ArithmeticOperators {
* Creates new {@link Subtract}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Subtract}.
*/
public static Subtract valueOf(AggregationExpression expression) {
@@ -1366,7 +1474,7 @@ public class ArithmeticOperators {
* Creates new {@link Subtract}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Subtract}.
*/
public static Subtract valueOf(Number value) {
@@ -1374,18 +1482,36 @@ public class ArithmeticOperators {
return new Subtract(Collections.singletonList(value));
}
/**
* Subtract the value stored at the given field.
*
* @param fieldReference must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Subtract subtract(String fieldReference) {
Assert.notNull(fieldReference, "FieldReference must not be null!");
return new Subtract(append(Fields.field(fieldReference)));
}
/**
* Subtract the evaluated value of the given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Subtract subtract(AggregationExpression expression) {
Assert.notNull(expression, "Expression must not be null!");
return new Subtract(append(expression));
}
/**
* Subtract the given value.
*
* @param value must not be {@literal null}.
* @return new instance of {@link Pow}.
*/
public Subtract subtract(Number value) {
return new Subtract(append(value));
}
@@ -1411,7 +1537,7 @@ public class ArithmeticOperators {
* Creates new {@link Trunc}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Trunc}.
*/
public static Trunc truncValueOf(String fieldReference) {
@@ -1423,7 +1549,7 @@ public class ArithmeticOperators {
* Creates new {@link Trunc}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Trunc}.
*/
public static Trunc truncValueOf(AggregationExpression expression) {
@@ -1435,7 +1561,7 @@ public class ArithmeticOperators {
* Creates new {@link Trunc}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link Trunc}.
*/
public static Trunc truncValueOf(Number value) {
@@ -1502,7 +1628,7 @@ public class ArithmeticOperators {
/**
* The place to round to. Can be between -20 and 100, exclusive.
*
* @param place
* @param place value between -20 and 100, exclusive.
* @return new instance of {@link Round}.
*/
public Round place(int place) {

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
* @return new instance of {@link ArrayOperatorFactory}.
*/
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
* @return new instance of {@link ArrayOperatorFactory}.
*/
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
* @return
* @param position the element index.
* @return new instance of {@link ArrayElemAt}.
*/
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
* @return new instance of {@link ArrayElemAt}.
*/
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
* @return new instance of {@link ArrayElemAt}.
*/
public ArrayElemAt elementAt(String fieldReference) {
@@ -170,7 +170,7 @@ public class ArrayOperators {
* {@literal arrayFieldReference} to it.
*
* @param arrayFieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ConcatArrays}.
*/
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
* @return new instance of {@link ConcatArrays}.
*/
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
* @return new instance of {@link AsBuilder} to create a {@link Filter}.
*/
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
* @return new instance of {@link IsArray}.
*/
public IsArray isArray() {
@@ -231,7 +231,7 @@ public class ArrayOperators {
/**
* Creates new {@link AggregationExpression} that takes the associated array and retrieves its length.
*
* @return
* @return new instance of {@link Size}.
*/
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
* @return new instance of {@link Slice}.
*/
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
* @return new instance of {@link IndexOfArray}.
*/
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
* @return new instance of {@link ReverseArray}.
*/
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
* @return new instance of {@link ReduceInitialValueBuilder} to create {@link Reduce}.
*/
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
* @return
* @param expressions must not be {@literal null}.
* @return new instance of {@link ReduceInitialValueBuilder} to create {@link Reduce}.
*/
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
* @return new instance of {@link Zip}.
*/
public Zip zipWith(Object... arrays) {
@@ -336,7 +336,7 @@ public class ArrayOperators {
* associated array.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link In}.
*/
public In containsValue(Object value) {
@@ -413,7 +413,7 @@ public class ArrayOperators {
* Creates new {@link ArrayElemAt}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ArrayElemAt}.
*/
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
* @return new instance of {@link ArrayElemAt}.
*/
public static ArrayElemAt arrayOf(AggregationExpression expression) {
@@ -446,16 +446,34 @@ 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!");
@@ -483,7 +501,7 @@ public class ArrayOperators {
* Creates new {@link ConcatArrays}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ConcatArrays}.
*/
public static ConcatArrays arrayOf(String fieldReference) {
@@ -495,7 +513,7 @@ public class ArrayOperators {
* Creates new {@link ConcatArrays}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link ConcatArrays}.
*/
public static ConcatArrays arrayOf(AggregationExpression expression) {
@@ -516,12 +534,24 @@ 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!");
@@ -574,7 +604,7 @@ public class ArrayOperators {
* Set the {@literal values} to apply the {@code $filter} to.
*
* @param values must not be {@literal null}.
* @return
* @return new instance of {@link AsBuilder} to create the {@link Filter}.
*/
public static AsBuilder filter(List<?> values) {
@@ -651,7 +681,7 @@ public class ArrayOperators {
* Set the {@literal variableName} for the elements in the input array.
*
* @param variableName must not be {@literal null}.
* @return
* @return never {@literal null}.
*/
ConditionBuilder as(String variableName);
}
@@ -665,7 +695,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
* @return never {@literal null}.
*/
Filter by(AggregationExpression expression);
@@ -673,7 +703,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
* @return never {@literal null}.
*/
Filter by(String expression);
@@ -681,7 +711,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
* @return never {@literal null}.
*/
Filter by(Document expression);
}
@@ -700,7 +730,7 @@ public class ArrayOperators {
/**
* Creates new {@link InputBuilder}.
*
* @return
* @return new instance of {@link FilterExpressionBuilder}.
*/
public static InputBuilder newBuilder() {
return new FilterExpressionBuilder();
@@ -800,7 +830,7 @@ public class ArrayOperators {
* Creates new {@link IsArray}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link IsArray}.
*/
public static IsArray isArray(String fieldReference) {
@@ -812,7 +842,7 @@ public class ArrayOperators {
* Creates new {@link IsArray}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link IsArray}.
*/
public static IsArray isArray(AggregationExpression expression) {
@@ -841,7 +871,7 @@ public class ArrayOperators {
* Creates new {@link Size}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Size}.
*/
public static Size lengthOfArray(String fieldReference) {
@@ -853,7 +883,7 @@ public class ArrayOperators {
* Creates new {@link Size}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Size}.
*/
public static Size lengthOfArray(AggregationExpression expression) {
@@ -895,7 +925,7 @@ public class ArrayOperators {
* Creates new {@link Slice}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Slice}.
*/
public static Slice sliceArrayOf(String fieldReference) {
@@ -907,7 +937,7 @@ public class ArrayOperators {
* Creates new {@link Slice}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Slice}.
*/
public static Slice sliceArrayOf(AggregationExpression expression) {
@@ -928,10 +958,22 @@ 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() {
@@ -978,7 +1020,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link IndexOfArray}.
*/
public static IndexOfArrayBuilder arrayOf(String fieldReference) {
@@ -990,7 +1032,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link IndexOfArray}.
*/
public static IndexOfArrayBuilder arrayOf(AggregationExpression expression) {
@@ -1002,7 +1044,7 @@ public class ArrayOperators {
* Start creating new {@link IndexOfArray}.
*
* @param values must not be {@literal null}.
* @return new instance of {@link IndexOfArray}.
* @return new instance of {@link IndexOfArrayBuilder} to create {@link IndexOfArray}.
* @since 2.2
*/
public static IndexOfArrayBuilder arrayOf(Collection<?> values) {
@@ -1011,6 +1053,12 @@ 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)));
}
@@ -1030,7 +1078,7 @@ public class ArrayOperators {
* Set the {@literal value} to check for its index in the array.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link IndexOfArray}.
*/
public IndexOfArray indexOf(Object value) {
@@ -1060,7 +1108,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link RangeOperatorBuilder} to create {@link RangeOperator}.
*/
public static RangeOperatorBuilder rangeStartingAt(String fieldReference) {
return new RangeOperatorBuilder(Fields.field(fieldReference));
@@ -1070,7 +1118,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link RangeOperatorBuilder} to create {@link RangeOperator}.
*/
public static RangeOperatorBuilder rangeStartingAt(AggregationExpression expression) {
return new RangeOperatorBuilder(expression);
@@ -1080,7 +1128,7 @@ public class ArrayOperators {
* Start creating new {@link RangeOperator}.
*
* @param value
* @return
* @return new instance of {@link RangeOperator}.
*/
public static RangeOperatorBuilder rangeStartingAt(long value) {
return new RangeOperatorBuilder(value);
@@ -1102,7 +1150,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param index
* @return
* @return new instance of {@link RangeOperator}.
*/
public RangeOperator to(long index) {
return new RangeOperator(Arrays.asList(startPoint, index));
@@ -1112,7 +1160,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link RangeOperator}.
*/
public RangeOperator to(AggregationExpression expression) {
return new RangeOperator(Arrays.asList(startPoint, expression));
@@ -1122,7 +1170,7 @@ public class ArrayOperators {
* Creates new {@link RangeOperator}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link RangeOperator}.
*/
public RangeOperator to(String fieldReference) {
return new RangeOperator(Arrays.asList(startPoint, Fields.field(fieldReference)));
@@ -1150,7 +1198,7 @@ public class ArrayOperators {
* Creates new {@link ReverseArray} given {@literal fieldReference}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ReverseArray}.
*/
public static ReverseArray reverseArrayOf(String fieldReference) {
return new ReverseArray(Fields.field(fieldReference));
@@ -1160,7 +1208,7 @@ public class ArrayOperators {
* Creates new {@link ReverseArray} given {@link AggregationExpression}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link ReverseArray}.
*/
public static ReverseArray reverseArrayOf(AggregationExpression expression) {
return new ReverseArray(expression);
@@ -1239,7 +1287,7 @@ public class ArrayOperators {
* Start creating new {@link Reduce}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link InitialValueBuilder} to create {@link Reduce}.
*/
public static InitialValueBuilder arrayOf(final String fieldReference) {
@@ -1267,7 +1315,7 @@ public class ArrayOperators {
Assert.notNull(expressions, "PropertyExpressions must not be null");
return new Reduce(Fields.field(fieldReference), initialValue,
Arrays.<AggregationExpression> asList(expressions));
Arrays.<AggregationExpression>asList(expressions));
}
};
}
@@ -1278,7 +1326,7 @@ public class ArrayOperators {
* Start creating new {@link Reduce}.
*
* @param arrayValueExpression must not be {@literal null}.
* @return
* @return new instance of {@link InitialValueBuilder} to create {@link Reduce}.
*/
public static InitialValueBuilder arrayOf(final AggregationExpression arrayValueExpression) {
@@ -1318,7 +1366,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
* @return never {@literal null}.
*/
ReduceBuilder withInitialValue(Object initialValue);
}
@@ -1335,7 +1383,7 @@ public class ArrayOperators {
* {@link Variable#VALUE} are available.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Reduce}.
*/
Reduce reduce(AggregationExpression expression);
@@ -1346,7 +1394,7 @@ public class ArrayOperators {
* {@link Variable#VALUE} are available.
*
* @param expressions must not be {@literal null}.
* @return
* @return new instance of {@link Reduce}.
*/
Reduce reduce(PropertyExpression... expressions);
}
@@ -1372,7 +1420,7 @@ public class ArrayOperators {
* Define a result property for an {@link AggregationExpression} used in {@link Reduce}.
*
* @param name must not be {@literal null}.
* @return
* @return new instance of {@link AsBuilder} to create {@link Reduce}.
*/
public static AsBuilder property(final String name) {
@@ -1402,7 +1450,7 @@ public class ArrayOperators {
* Set the {@link AggregationExpression} resulting in the properties value.
*
* @param expression must not be {@literal null}.
* @return
* @return never {@literal null}.
*/
PropertyExpression definedAs(AggregationExpression expression);
}
@@ -1459,7 +1507,7 @@ public class ArrayOperators {
* eg. {@code $$value.product}
*
* @param property must not be {@literal null}.
* @return
* @return never {@literal null}.
*/
public Field referringTo(final String property) {
@@ -1508,7 +1556,7 @@ public class ArrayOperators {
* Start creating new {@link Zip}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link ZipBuilder} to create {@link Zip}.
*/
public static ZipBuilder arrayOf(String fieldReference) {
@@ -1520,7 +1568,7 @@ public class ArrayOperators {
* Start creating new {@link Zip}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link ZipBuilder} to create {@link Zip}.
*/
public static ZipBuilder arrayOf(AggregationExpression expression) {
@@ -1544,7 +1592,7 @@ public class ArrayOperators {
/**
* Create new {@link Zip} and set the {@code useLongestLength} property to {@literal true}.
*
* @return
* @return new instance of {@link Zip}.
*/
public Zip useLongestLength() {
return new Zip(append("useLongestLength", true));
@@ -1554,7 +1602,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Zip}.
*/
public Zip defaultTo(String fieldReference) {
@@ -1566,7 +1614,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link Zip}.
*/
public Zip defaultTo(AggregationExpression expression) {
@@ -1578,7 +1626,7 @@ public class ArrayOperators {
* Optionally provide a default value.
*
* @param array must not be {@literal null}.
* @return
* @return new instance of {@link Zip}.
*/
public Zip defaultTo(Object[] array) {
@@ -1602,7 +1650,7 @@ public class ArrayOperators {
* array, etc.
*
* @param arrays arrays to zip the referenced one with. must not be {@literal null}.
* @return
* @return new instance of {@link Zip}.
*/
public Zip zip(Object... arrays) {
@@ -1616,7 +1664,7 @@ public class ArrayOperators {
}
}
return new Zip(Collections.<String, Object> singletonMap("inputs", sourceArrays));
return new Zip(Collections.<String, Object>singletonMap("inputs", sourceArrays));
}
}
}
@@ -1627,7 +1675,7 @@ public class ArrayOperators {
* @author Christoph Strobl
* @author Shashank Sharma
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/in/">https://docs.mongodb.com/manual/reference/operator/aggregation/in/</a>
* "https://docs.mongodb.com/manual/reference/operator/aggregation/in/">https://docs.mongodb.com/manual/reference/operator/aggregation/in/</a>
* @since 2.2
*/
public static class In extends AbstractAggregationExpression {
@@ -1645,7 +1693,7 @@ public class ArrayOperators {
* Start creating {@link In}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link InBuilder} to create {@link In}.
*/
public static InBuilder arrayOf(String fieldReference) {
@@ -1662,7 +1710,7 @@ public class ArrayOperators {
* Start creating {@link In}.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link InBuilder} to create {@link In}.
*/
public static InBuilder arrayOf(AggregationExpression expression) {
@@ -1704,7 +1752,7 @@ public class ArrayOperators {
* Set the {@literal value} to check for existence in the array.
*
* @param value must not be {@literal value}.
* @return
* @return new instance of {@link In}.
*/
In containsValue(Object value);
}
@@ -1716,7 +1764,7 @@ public class ArrayOperators {
*
* @author Christoph Strobl
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/">https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/</a>
* "https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/">https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/</a>
* @since 2.1
*/
public static class ArrayToObject extends AbstractAggregationExpression {

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
* @return new instance of {@link BooleanOperatorFactory}.
*/
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
* @return new instance of {@link BooleanOperatorFactory}.
*/
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
* @return new instance of {@link Not}.
*/
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
* @return new instance of {@link Not}.
*/
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
* @return new instance of {@link And}.
*/
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
* @return new instance of {@link And}.
*/
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
* @return new instance of {@link Or}.
*/
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
* @return new instance of {@link Or}.
*/
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
* @return new instance of {@link Not}.
*/
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
* @return
* @param expressions must not be {@literal null}.
* @return new instance of {@link And}.
*/
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
* @return new instance of {@link And}.
*/
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
* @return new instance of {@link And}.
*/
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
* @return new instance of {@link And}.
*/
public And andValue(Object value) {
@@ -263,7 +263,7 @@ public class BooleanOperators {
* expressions are {@literal true}.
*
* @param expressions must not be {@literal null}.
* @return
* @return new instance of {@link Or}.
*/
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
* @return new instance of {@link Or}.
*/
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
* @return new instance of {@link Or}.
*/
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
* @return new instance of {@link Or}.
*/
public Or orValue(Object value) {
@@ -329,7 +329,7 @@ public class BooleanOperators {
* value.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Not}.
*/
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
* @return new instance of {@link Not}.
*/
public static Not not(AggregationExpression expression) {

View File

@@ -15,12 +15,11 @@
*/
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
@@ -106,14 +105,23 @@ public class BucketAutoOperation extends BucketOperationSupport<BucketAutoOperat
options.putAll(super.toDocument(context));
return new Document("$bucketAuto", options);
return new Document(getOperator(), options);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator()
*/
@Override
public String getOperator() {
return "$bucketAuto";
}
/**
* Configures a number of bucket {@literal buckets} and return a new {@link BucketAutoOperation}.
*
* @param buckets must be a positive number.
* @return
* @return new instance of {@link BucketAutoOperation}.
*/
public BucketAutoOperation withBuckets(int buckets) {
@@ -128,7 +136,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
* @return new instance of {@link BucketAutoOperation}.
*/
public BucketAutoOperation withGranularity(Granularity granularity) {
@@ -209,7 +217,7 @@ public class BucketAutoOperation extends BucketOperationSupport<BucketAutoOperat
*
* @param expression must not be {@literal null}.
* @param operation must not be {@literal null}.
* @param parameters
* @param parameters must not be {@literal null}.
*/
protected ExpressionBucketAutoOperationBuilder(String expression, BucketAutoOperation operation,
Object[] parameters) {

View File

@@ -20,21 +20,19 @@ 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 />
*
* Bucket stage is typically used with {@link Aggregation} and {@code $facet}. Categorizes incoming documents into
* groups, called buckets, based on a specified expression and bucket boundaries. <br />
*
* We recommend to use the static factory method {@link Aggregation#bucket(String)} instead of creating instances of
* this class directly.
*
* @see <a href="https://docs.mongodb.org/manual/reference/aggregation/bucket/">https://docs.mongodb.org/manual/reference/aggregation/bucket/</a>
* @see <a href=
* "https://docs.mongodb.org/manual/reference/aggregation/bucket/">https://docs.mongodb.org/manual/reference/aggregation/bucket/</a>
* @see BucketOperationSupport
* @author Mark Paluch
* @since 1.10
@@ -103,14 +101,23 @@ public class BucketOperation extends BucketOperationSupport<BucketOperation, Buc
options.putAll(super.toDocument(context));
return new Document("$bucket", options);
return new Document(getOperator(), options);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator()
*/
@Override
public String getOperator() {
return "$bucket";
}
/**
* Configures a default bucket {@literal literal} and return a new {@link BucketOperation}.
*
* @param literal must not be {@literal null}.
* @return
* @return new instance of {@link BucketOperation}.
*/
public BucketOperation withDefaultBucket(Object literal) {
@@ -123,7 +130,7 @@ public class BucketOperation extends BucketOperationSupport<BucketOperation, Buc
* preserved and the new {@literal boundaries} are appended.
*
* @param boundaries must not be {@literal null}.
* @return
* @return new instance of {@link BucketOperation}.
*/
public BucketOperation withBoundaries(Object... boundaries) {
@@ -204,12 +211,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
* @param parameters must not be {@literal null}.
*/
protected ExpressionBucketOperationBuilder(String expression, BucketOperation operation, Object[] parameters) {
super(expression, operation, parameters);

View File

@@ -21,14 +21,13 @@ 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 />
@@ -104,7 +103,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
* @return new instance of {@link ExpressionBucketOperationBuilderSupport} to create {@link BucketOperation}.
*/
public abstract ExpressionBucketOperationBuilderSupport<B, T> andOutputExpression(String expression,
Object... params);
@@ -114,7 +113,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
* @return never {@literal null}.
*/
public abstract B andOutput(AggregationExpression expression);
@@ -124,14 +123,14 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* {@literal fieldName}.
*
* @param fieldName must not be {@literal null} or empty.
* @return
* @return never {@literal null}.
*/
public abstract B andOutput(String fieldName);
/**
* Creates a new {@link BucketOperationSupport} given to add a count field to the resulting bucket documents.
*
* @return
* @return never {@literal null}.
*/
public B andOutputCount() {
return andOutput(new AggregationExpression() {
@@ -231,7 +230,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
* @return never {@literal null}.
*/
public B count() {
return sum(1);
@@ -240,7 +239,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $sum}-expression for the current value.
*
* @return
* @return never {@literal null}.
*/
public B sum() {
return apply(Accumulators.SUM);
@@ -249,8 +248,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $sum}-expression for the given {@literal value}.
*
* @param value
* @return
* @param value must not be {@literal null}.
* @return never {@literal null}.
*/
public B sum(Number value) {
return apply(new OperationOutput(Accumulators.SUM.getMongoOperator(), Collections.singleton(value)));
@@ -259,7 +258,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $last}-expression for the current value..
*
* @return
* @return never {@literal null}.
*/
public B last() {
return apply(Accumulators.LAST);
@@ -268,7 +267,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for a {@code $first}-expression the current value.
*
* @return
* @return never {@literal null}.
*/
public B first() {
return apply(Accumulators.FIRST);
@@ -277,8 +276,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $avg}-expression for the current value.
*
* @param reference
* @return
* @return never {@literal null}.
*/
public B avg() {
return apply(Accumulators.AVG);
@@ -287,7 +285,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $min}-expression for the current value.
*
* @return
* @return never {@literal null}.
*/
public B min() {
return apply(Accumulators.MIN);
@@ -296,7 +294,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $max}-expression for the current value.
*
* @return
* @return never {@literal null}.
*/
public B max() {
return apply(Accumulators.MAX);
@@ -305,7 +303,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $push}-expression for the current value.
*
* @return
* @return never {@literal null}.
*/
public B push() {
return apply(Accumulators.PUSH);
@@ -314,7 +312,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Generates a builder for an {@code $addToSet}-expression for the current value.
*
* @return
* @return never {@literal null}.
*/
public B addToSet() {
return apply(Accumulators.ADDTOSET);
@@ -325,7 +323,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
* @return never {@literal null}.
*/
public B apply(String operation, Object... values) {
@@ -342,7 +340,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
* Apply an {@link OperationOutput} to this output.
*
* @param operationOutput must not be {@literal null}.
* @return
* @return never {@literal null}.
*/
protected abstract B apply(OperationOutput operationOutput);
@@ -354,7 +352,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
* @return never {@literal null}.
*/
public T as(String alias) {
@@ -550,8 +548,7 @@ 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) {
@@ -579,7 +576,7 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Returns the field that holds the {@link ProjectionOperationBuilder.OperationProjection}.
*
* @return
* @return never {@literal null}.
*/
protected Field getField() {
return getExposedField();
@@ -589,7 +586,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
* @return new instance of {@link OperationOutput}.
*/
public OperationOutput withAlias(String alias) {
@@ -658,8 +655,8 @@ public abstract class BucketOperationSupport<T extends BucketOperationSupport<T,
/**
* Creates a new {@link AggregationExpressionOutput}.
*
* @param field
* @param expression
* @param field must not be {@literal null}.
* @param expression must not be {@literal null}.
*/
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
* @return new instance of {@link ComparisonOperatorFactory}.
*/
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
* @return new instance of {@link ComparisonOperatorFactory}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Lte}.
*/
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
* @return
* @param value must not be {@literal null}.
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
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
* @return new instance of {@link Cmp}.
*/
public Cmp compareToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Cmp(append(value));
return new Cmp(append(value, Expand.KEEP_SOURCE));
}
}
@@ -435,7 +435,7 @@ public class ComparisonOperators {
* Creates new {@link Eq}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
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
* @return new instance of {@link Eq}.
*/
public Eq equalToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Eq(append(value));
return new Eq(append(value, Expand.KEEP_SOURCE));
}
}
@@ -512,7 +512,7 @@ public class ComparisonOperators {
* Creates new {@link Gt}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
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
* @return new instance of {@link Gt}.
*/
public Gt greaterThanValue(Object value) {
@@ -589,7 +589,7 @@ public class ComparisonOperators {
* Creates new {@link Lt}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
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
* @return new instance of {@link Lt}.
*/
public Lt lessThanValue(Object value) {
@@ -666,7 +666,7 @@ public class ComparisonOperators {
* Creates new {@link Gte}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
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
* @return new instance of {@link Gte}.
*/
public Gte greaterThanEqualToValue(Object value) {
@@ -743,7 +743,7 @@ public class ComparisonOperators {
* Creates new {@link Lte}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Lte}.
*/
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
* @return new instance of {@link Lte}.
*/
public Lte lessThanEqualToValue(Object value) {
@@ -820,7 +820,7 @@ public class ComparisonOperators {
* Creates new {@link Ne}.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
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
* @return new instance of {@link Ne}.
*/
public Ne notEqualToValue(Object value) {
Assert.notNull(value, "Value must not be null!");
return new Ne(append(value));
return new Ne(append(value, Expand.KEEP_SOURCE));
}
}
}

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
* @return new instance of {@link ConditionalOperatorFactory}.
*/
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
* @return new instance of {@link ConditionalOperatorFactory}.
*/
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
* @return new instance of {@link ConditionalOperatorFactory}.
*/
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
* @return new instance of {@link IfNull.ThenBuilder} to create {@link IfNull}.
*/
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
* @return new instance of {@link IfNull.ThenBuilder} to create {@link IfNull}.
*/
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
* @return new instance of {@link Switch}.
*/
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
* @return new instance of {@link Switch}.
*/
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
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
*/
public OtherwiseBuilder then(Object value) {
@@ -189,7 +189,7 @@ public class ConditionalOperators {
* return expressions.
*
* @param expression must not be {@literal null}.
* @return
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
*/
public OtherwiseBuilder thenValueOf(AggregationExpression expression) {
@@ -202,7 +202,7 @@ public class ConditionalOperators {
* return expressions.
*
* @param fieldReference must not be {@literal null}.
* @return
* @return new instance of {@link OtherwiseBuilder} to create {@link Cond}.
*/
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.
*
* @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
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/">https://docs.mongodb.com/manual/reference/operator/aggregation/ifNull/</a>
*/
public static class IfNull implements AggregationExpression {
@@ -251,9 +251,8 @@ 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
* @param fieldReference the field to check for a {@literal null} value, field reference must not be {@literal null}.
* @return never {@literal null}.
*/
public static ThenBuilder ifNull(String fieldReference) {
@@ -265,8 +264,8 @@ public class ConditionalOperators {
* Creates new {@link IfNull}.
*
* @param expression the expression to check for a {@literal null} value, field reference must not be
* {@literal null}.
* @return
* {@literal null}.
* @return never {@literal null}.
*/
public static ThenBuilder ifNull(AggregationExpression expression) {
@@ -316,14 +315,14 @@ public class ConditionalOperators {
/**
* @param fieldReference the field to check for a {@literal null} value, field reference must not be
* {@literal null}.
* {@literal null}.
* @return the {@link ThenBuilder}
*/
ThenBuilder ifNull(String fieldReference);
/**
* @param expression the expression to check for a {@literal null} value, field name must not be {@literal null}
* or empty.
* or empty.
* @return the {@link ThenBuilder}
*/
ThenBuilder ifNull(AggregationExpression expression);
@@ -336,21 +335,21 @@ 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
* {@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}.
*/
IfNull then(Object value);
/**
* @param fieldReference the field holding the replacement value, must not be {@literal null}.
* @return
* @return new instance of {@link IfNull}.
*/
IfNull thenValueOf(String fieldReference);
/**
* @param expression the expression yielding to the replacement value, must not be {@literal null}.
* @return
* @return new instance of {@link IfNull}.
*/
IfNull thenValueOf(AggregationExpression expression);
}
@@ -364,7 +363,8 @@ public class ConditionalOperators {
private @Nullable Object condition;
private IfNullOperatorBuilder() {}
private IfNullOperatorBuilder() {
}
/**
* Creates a new builder for {@link IfNull}.
@@ -458,9 +458,15 @@ public class ConditionalOperators {
public static Switch switchCases(List<CaseOperator> conditions) {
Assert.notNull(conditions, "Conditions must not be null!");
return new Switch(Collections.<String, Object> singletonMap("branches", new ArrayList<CaseOperator>(conditions)));
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));
}
@@ -522,7 +528,7 @@ public class ConditionalOperators {
* Set the then {@literal value}.
*
* @param value must not be {@literal null}.
* @return
* @return new instance of {@link CaseOperator}.
*/
CaseOperator then(Object value);
}
@@ -536,10 +542,10 @@ public class ConditionalOperators {
* {@link AggregationExpression expressions}, values of simple MongoDB types or values that can be converted to a
* simple MongoDB type.
*
* @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
* @see <a href=
* "https://docs.mongodb.com/manual/reference/operator/aggregation/cond/">https://docs.mongodb.com/manual/reference/operator/aggregation/cond/</a>
*/
public static class Cond implements AggregationExpression {
@@ -664,7 +670,6 @@ public class ConditionalOperators {
}
clauses.add(new Document(key, args));
} else if (predicate instanceof Document) {
Document nested = (Document) predicate;
@@ -680,7 +685,6 @@ public class ConditionalOperators {
args.add(nested.get(s));
clauses.add(new Document(s, args));
}
} else if (!isKeyword(key)) {
List<Object> args = new ArrayList<Object>();
@@ -802,8 +806,8 @@ public class ConditionalOperators {
/**
* @param value the value to be used if the 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}.
* value that is supported by MongoDB or a value that can be converted to a MongoDB representation but
* must not be {@literal null}.
* @return the {@link OtherwiseBuilder}
*/
OtherwiseBuilder then(Object value);
@@ -828,8 +832,8 @@ public class ConditionalOperators {
/**
* @param value the value to be used if the condition evaluates {@literal false}. 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}.
* value that is supported by MongoDB or a value that can be converted to a MongoDB representation but
* must not be {@literal null}.
* @return the {@link Cond}
*/
Cond otherwise(Object value);
@@ -857,7 +861,8 @@ public class ConditionalOperators {
private @Nullable Object condition;
private @Nullable Object thenValue;
private ConditionalExpressionBuilder() {}
private ConditionalExpressionBuilder() {
}
/**
* Creates a new builder for {@link Cond}.

View File

@@ -34,9 +34,9 @@ public class CountOperation implements FieldsExposingAggregationOperation {
private final String fieldName;
/**
* Creates a new {@link CountOperation} given the {@link fieldName} field name.
* Creates a new {@link CountOperation} given the {@literal fieldName} field name.
*
* @param asFieldName must not be {@literal null} or empty.
* @param fieldName must not be {@literal null} or empty.
*/
public CountOperation(String fieldName) {
@@ -49,7 +49,12 @@ public class CountOperation implements FieldsExposingAggregationOperation {
*/
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$count", fieldName);
return new Document(getOperator(), fieldName);
}
@Override
public String getOperator() {
return "$count";
}
/* (non-Javadoc)
@@ -71,7 +76,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
* @return new instance of {@link CountOperation}.
*/
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
* @return new instance of {@link Type}.
*/
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
* @return new instance of {@link Type}.
*/
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
* @return new instance of {@link DateOperatorFactory}.
*/
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
* @return new instance of {@link DateOperatorFactory}.
*/
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
* @return new instance of {@link DayOfYear}.
*/
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
* @return new instance of {@link DayOfMonth}.
*/
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
* @return new instance of {@link DayOfWeek}.
*/
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
* @return new instance of {@link Year}.
*/
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
* @return new instance of {@link Month}.
*/
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
* @return new instance of {@link Week}.
*/
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
* @return new instance of {@link Hour}.
*/
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
* @return new instance of {@link Minute}.
*/
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
* @return new instance of {@link Second}.
*/
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
* @return new instance of {@link Millisecond}.
*/
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
* @return new instance of {@link DateToString}.
*/
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
* @return new instance of {@link IsoDayOfWeek}.
*/
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
* @return new instance of {@link IsoWeek}.
*/
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
* @return new instance of {@link IsoWeekYear}.
*/
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
* @return new instance of {@link DayOfYear}.
*/
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
* @return new instance of {@link DayOfYear}.
*/
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
* @return new instance of {@link DayOfMonth}.
*/
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
* @return new instance of {@link DayOfMonth}.
*/
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
* @return new instance of {@link DayOfWeek}.
*/
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
* @return new instance of {@link DayOfWeek}.
*/
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
* @return new instance of {@link Year}.
*/
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
* @return new instance of {@link Year}.
*/
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
* @return new instance of {@link Month}.
*/
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
* @return new instance of {@link Month}.
*/
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
* @return new instance of {@link Week}.
*/
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
* @return new instance of {@link Week}.
*/
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
* @return new instance of {@link Hour}.
*/
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
* @return new instance of {@link Hour}.
*/
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
* @return new instance of {@link Minute}.
*/
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
* @return new instance of {@link Minute}.
*/
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
* @return new instance of {@link Second}.
*/
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
* @return new instance of {@link Second}.
*/
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
* @return new instance of {@link Millisecond}.
*/
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
* @return new instance of {@link Millisecond}.
*/
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
* @return new instance of {@link FormatBuilder} to crate {@link DateToString}.
*/
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
* @return new instance of {@link FormatBuilder} to crate {@link DateToString}.
*/
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
* @return new instance of {@link IsoDayOfWeek}.
*/
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
* @return new instance of {@link IsoDayOfWeek}.
*/
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
* @return new instance of {@link IsoWeek}.
*/
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
* @return new instance of {@link IsoWeek}.
*/
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
* @return new instance of {@link IsoWeekYear}.
*/
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
* @return new instance of {@link IsoWeekYear}.
*/
public static IsoWeekYear isoWeekYearOf(AggregationExpression expression) {
@@ -2378,6 +2378,7 @@ 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

@@ -71,6 +71,15 @@ abstract class DocumentEnhancingOperation implements InheritsFieldsAggregationOp
*/
protected abstract String mongoOperator();
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator()
*/
@Override
public String getOperator() {
return mongoOperator();
}
/**
* @return the raw value map
*/

View File

@@ -46,7 +46,7 @@ public final class ExposedFields implements Iterable<ExposedField> {
/**
* Returns an empty {@link ExposedFields} instance.
*
* @return
* @return never {@literal null}.
* @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
* @return never {@literal null}.
*/
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
* @return never {@literal null}.
*/
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
* @return never {@literal null}.
*/
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
* @return never {@literal null}.
*/
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
* @return never {@literal null}.
*/
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
* @return new instance of {@link ExposedFields}.
*/
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
* @return
* @param name must not be {@literal null}.
* @return can be {@literal null}.
*/
@Nullable
public ExposedField getField(String name) {

View File

@@ -149,4 +149,12 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo
}
return null;
}
/**
* @return obtain the root context used to resolve references.
* @since 3.1
*/
AggregationOperationContext getRootContext() {
return rootContext;
}
}

View File

@@ -20,12 +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.BucketOperationSupport.Output;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
import org.springframework.util.Assert;
import org.bson.Document;
/**
* Encapsulates the aggregation framework {@code $facet}-operation. <br />
* Facet of {@link AggregationOperation}s to be used in an {@link Aggregation}. Processes multiple
@@ -84,7 +83,16 @@ public class FacetOperation implements FieldsExposingAggregationOperation {
*/
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$facet", facets.toDocument(context));
return new Document(getOperator(), facets.toDocument(context));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator()
*/
@Override
public String getOperator() {
return "$facet";
}
/* (non-Javadoc)

View File

@@ -16,14 +16,12 @@
package org.springframework.data.mongodb.core.aggregation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
/**
@@ -95,21 +93,27 @@ public class GeoNearOperation implements AggregationOperation {
Document command = context.getMappedObject(nearQuery.toDocument());
if(command.containsKey("query")) {
if (command.containsKey("query")) {
command.replace("query", context.getMappedObject(command.get("query", Document.class)));
}
if(command.containsKey("collation")) {
command.remove("collation");
}
command.remove("collation");
command.put("distanceField", distanceField);
if (StringUtils.hasText(indexKey)) {
command.put("key", indexKey);
}
return new Document("$geoNear", command);
return new Document(getOperator(), command);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator()
*/
@Override
public String getOperator() {
return "$geoNear";
}
/*
@@ -125,11 +129,11 @@ public class GeoNearOperation implements AggregationOperation {
List<Document> stages = new ArrayList<>();
stages.add(command);
if(nearQuery.getSkip() != null && nearQuery.getSkip() > 0){
if (nearQuery.getSkip() != null && nearQuery.getSkip() > 0) {
stages.add(new Document("$skip", nearQuery.getSkip()));
}
if(limit != null) {
if (limit != null) {
stages.add(new Document("$limit", limit.longValue()));
}

View File

@@ -119,7 +119,12 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
graphLookup.put("restrictSearchWithMatch", context.getMappedObject(restrictSearchWithMatch.getCriteriaObject()));
}
return new Document("$graphLookup", graphLookup);
return new Document(getOperator(), graphLookup);
}
@Override
public String getOperator() {
return "$graphLookup";
}
/*
@@ -146,7 +151,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
* @return never {@literal null}.
*/
StartWithBuilder from(String collectionName);
}
@@ -161,7 +166,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
* @return never {@literal null}.
*/
ConnectFromBuilder startWith(String... fieldReferences);
@@ -169,7 +174,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
* @return never {@literal null}.
*/
ConnectFromBuilder startWith(AggregationExpression... expressions);
@@ -178,7 +183,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* {@link AggregationExpression} to apply the {@code $graphLookup} to.
*
* @param expressions must not be {@literal null}.
* @return
* @return never {@literal null}.
* @throws IllegalArgumentException
*/
ConnectFromBuilder startWith(Object... expressions);
@@ -193,7 +198,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
* @return never {@literal null}.
*/
ConnectToBuilder connectFrom(String fieldName);
}
@@ -207,7 +212,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
* @return never {@literal null}.
*/
GraphLookupOperationBuilder connectTo(String fieldName);
}
@@ -360,7 +365,7 @@ public class GraphLookupOperation implements InheritsFieldsAggregationOperation
* Optionally limit the number of recursions.
*
* @param numberOfRecursions must be greater or equal to zero.
* @return
* @return this.
*/
public GraphLookupOperationBuilder maxDepth(long numberOfRecursions) {
@@ -374,7 +379,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
* @return this.
*/
public GraphLookupOperationBuilder depthField(String fieldName) {

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