With the introduction of AggregationStage we move the API closer to the MongoDB terminology removing kognitive overhead.
Also the change allows us to switch back and forth with the default implementations of toDocument and toDocuments which let's us remove the deprecation warnings having dedicated interfaces that indicate what to implement in order to comply with the usage pattern.
Implement ReadConcernAware and ReadPreferenceAware for NearQuery and make sure those get applied when working with the template API.
Original Pull Request: #4288
Reuse Let from VariableOperators.
Limit API exposure and favor builders.
Update nullability constraints and assertions.
Update integration tests.
Add unit tests.
Original Pull Request: #4272
This commit adds missing reflection configuration for Querydsl integration. We now also make sure to call the queryMixing getter instead of reading the field via reflection.
Closes#4244
Original pull request: #4245
We now use the springDocsUrl attribute provided via spring-projects/spring-data-build#1895 to resolve links to framework documentation.
Original Pull Request: #4267
In some cases the users domain model may hold references to spring data or MongoDB specific types which should not be included in the reflection configuration as they are part of the static runtime hints configuration.
Closes#4248
Original pull request: #4249
This commit fixes an issue where an existing Id got replaced with a generated one when using MongoId annotation.
Closes: #4184Closes: #4197
Original pull request: #4203.
Introduce CollectionChangeStreamOptions which allows to define the changeStreamPreAndPostImages of the createCollection command.
Original Pull Request: #4193
Update Javadoc to mention unit of measure for min/maxDistance depending on usage of geoJson.
Also remove unused imports from tests
See #4004
Original pull request: #4006.
$near and $nearSphere queries are not supported via countDocuments and the used aggregation match stage and need to be rewritten to $geoWithin. The existing logic did not cover usage of geoJson types, which is fixed now. In case of nearSphere it is also required to convert the $maxDistance argument (given in meters for geoJson) to radians which is used by $geoWithin $centerSphere.
Closes#4004
Original pull request: #4006.
Related to #2925
We now make sure to provide an id value that matches the desired target type when no id is set, and the property defines an explicit conversion target.
Previously a new ObjectId would have been generated which leads to type inconsistencies when querying for _id.
Closes#4026
Original pull request: #4057.
We now make sure to convert references in update operations targeting collection like fields when using eg. the push modifier.
Closes#4041
Original pull request: #4045.
We now provide a better worded exception message when trying to derive the collection name for a type that is not considered a user types (such as org.bson.Document).
Update the Javadoc to hint to the error.
Closes#4061
Original pull request: #4062.
We now make sure to apply the token to startAfter method of the driver. Before this change it had been incorrectly applied to resumeAfter.
Closes#4167.
Original pull request: #4168.
As of spring-projects/spring-framework#29125,
`StreamUtils..emptyInput()` is deprecated in favor of
`InputStream.nullInputStream()` from the JDK.
Closes: #4160
The Collation annotation mainly serves as a meta annotation that allows common access to retrieving collation values for annotated queries, aggregations, etc.
Original Pull Request: #4131
We now make sure to run the enhancer during AOT which allows the infrastructure to pick up the generated type.
Along the lines we removed the no longer supported asserts for class proxies and followed changes in FW6.
Closes: #4148
This commit ensures to fully resolve non association values from the given source document instead of trying attempt a by id lookup in already resolved instances.
Closes: #4098
Original pull request: #4133.
We now correctly instantiate DTO projection classes by using the actual constructor argument type. Previously, we did not update the conversion context to fetch the correct type but used the type of the DTO projection class instead of the constructor argument.
Closes#4120
We now use the AOT infrastructure of Spring Framework 6 and data commons to provide AOT support building the foundation for native image compilation.
Additionally we register hints for GraalVM native image.
See: #4022
Original Pull Request: #4093
We now ensure to not override `ValidatingMongoEventListener` and `LocalValidatorFactoryBean` bean definitions by avoiding duplicate registrations and checking whether a bean with the given name is already registered.
Closes#4087
Introduce Aggregation.stage which allows to use a plain JSON String or any valid Bson representation to be used within an aggregation pipeline stage, without having to implement AggregationOperation directly.
The change allows to make use of driver native builder API for aggregates.
Original pull request: #4059.
Closes#4038
Refine API naming towards merge/property instead of combine/specify. Tweak documentation. Introduce Resolution.ofValue(…) for easier creation.
See #3870
Original pull request: #3986.
This commit introduces MergedJsonSchema and MergedJsonSchemaProperty that can be used to merge properties of multiple objects into one as long as the additions do not conflict with another (eg. due to usage of different types).
To resolve previously mentioned errors it is required to provide a ConflictResolutionFunction.
Closes#3870
Original pull request: #3986.
We now create a new conversion context to ensure that we use the correct property type to avoid type retention when mapping complex objects within a projection.
Closes#3998
This commit fixes an issue when creating a collection via MongoTemplate without passing on type information. In this case potential time series information was lost.
Closes#3984
Original pull request: #3990.
This commit introduce an option that allows users to opt in on using estimatedDocumentCount instead of countDocuments in case the used filter query is empty.
To still be able to retrieve the exact number of matching documents we also introduced MongoTemplate#exactCount.
Closes: #3522
Original pull request: #3951.
Switch update execution to an annotation based model that allows usage of both the classic update as well as the aggregation pipeline variant. Add the reactive variant of it.
Make sure to allow parameter binding for update expressions and verify method return types.
Update Javadoc and reference documentation.
See: #2107
Original Pull Request: #284
Upgrade to data-commons 3.0 and Java 17 (still source level 16 due to asm).
Remove support for threeten, joda-time.
Transition to PersistentEntitiesFactoryBean from data-commons.
Update build to MongoDB 4.4 and 5 with Java17. Remove Java8 setup.
Fix javadoc tooling error on cdi 1 vs. 2 version mix.
Disabled internal package cycle analysis as this requires transition to ArchUnit.
By reading a properties file from an external location, it is possible to inject a consistent set of properties from Spring Data Build. This also supports repeatable builds.
Closes#3949.
This commit registers the first(...) and last(...) methods for transformation via SpEL.
Also update reference and java documentation and add issue reference to tests.
Original Pull Request: #3866
Add tests and move json string treatment into the ParameterBindingDocumentCodec.
Finally add issue references and format code.
Original Pull Request: #3907
This fix enables defining an entire JSON-based query in Query and Aggregate annotations using a single parameter or SpEL Expression.
Resolves: #3871
Original Pull Request: #3907
To avoid driver configuration specific UUID representation format errors (binary subtype 3 vs. subtype 4) we now directly convert the given key into its subtype 4 format.
Resolves: #3929
Original pull request: #3931.
This commit removes usage of the iterator and replaces map key and positional parameter mappings with an index based token lookup.
Closes#3921
Original pull request: #3930.
This commit makes sure to exclude Map like structures from index inspection unless annotated with WilcardIndexed.
Closes#3914, closes#3901
Original pull request: #3915.
We now set the ClassLoader from the ApplicationContext to the type mapper to ensure the type mapper has access to entities. Previously, `SimpleTypeInformationMapper` used the contextual class loader and that failed in Fork/Join-Pool threads such as parallel streams as ForkJoinPool uses the system classloader. Running e.g. a packaged Boot application sets up an application ClassLoader that has access to packaged code while the system ClassLoader does not.
Also, consistently access the MongoTypeMapper through its getter.
Closes#3905
We now support the functional fluent query definition API for imperative and reactive usage with Querydsl and Query by Example.
Page<PersonProjection> first = repository.findBy(Example.of(probe),
it -> it.as(PersonProjection.class).project("firstname").page(PageRequest.of(0, 1, Sort.by("firstname"))));
Closes#3757
Original pull request: #3788.
We now consider using the target keyword when computing document references. This fixes an issue where query/update statements had not been rendered correctly for references like { 'name' : ?#{#target} }.
Closes#3853
Original pull request: #3856.
This commit makes sure that the string to ObjectId conversion when storing document references follows the general conversion rules.
Closes#3847
Original pull request: #3848.
MongoDB has alpha releases in a slightly different location on their distribution server. And they use different keys for signing these alpha releases compared to the overall package listing.
Closes#3696
Original pull request: #3753.
Update assertions for changed return types, add a bit of think time and disable tests for no longer supported features.
See #3696
Original pull request: #3753.
This commit introduces support for creating a MongoJsonSchema containing encrypted fields for a given type based on mapping metadata.
Using the Encrypted annotation allows to derive required encryptMetadata and encrypt properties within a given (mapping)context.
@Document
@Encrypted(keyId = "...")
static class Patient {
// ...
@Encrypted(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
private Integer ssn;
}
MongoJsonSchemaCreator schemaCreator = MongoJsonSchemaCreator.create(mappingContext);
MongoJsonSchema patientSchema = schemaCreator
.filter(MongoJsonSchemaCreator.encryptedOnly())
.createSchemaFor(Patient.class);
Closes: #3800
Original pull request: #3801.
Introduce EmptyDocument and utility methods in BsonUtils. Avoid entrySet and iterator creation for document iterations/inspections.
Relates to: #3760
Original Pull Request: #3809
SessionSynchronization.NEVER bypasses all transactional integration in cases where applications do not want to make use of transactions so that transaction inspection overhead is avoided.
Closes: #3760
Original Pull Request: #3809
We now simply delegate to AnnotationBasedPersistentProperty.isIdProperty() for the detection of annotated identifiers. The previous, manual identifier check was preventing additional identifier annotations, supported by ABP, to be considered, too.
Fixes#3803.
This commit adds support for relational style One-To-Many references using a combination of ReadonlyProperty and @DocumentReference.
It allows to link types without explicitly storing the linking values within the document itself.
@Document
class Publisher {
@Id
ObjectId id;
// ...
@ReadOnlyProperty
@DocumentReference(lookup="{'publisherId':?#{#self._id} }")
List<Book> books;
}
Closes: #3798
Original pull request: #3802.
We now no longer attempt to convert query Documents into primitive types to avoid e.g. Document to String conversion.
Closes: #3783
Original Pull Request: #3797
This commit fixes an issue where a defined custom target type conversion for the id field was not properly considered when writing a document reference. Previously an eg. String was not being converted into an ObjectId correctly causing lookup queries to return empty results.
Converting the id property value on write solves the issue.
Includes a minor polish in the mapping centralizing pointer creation within the DocumentPointerFactory.
Closes: #3782
Original pull request: #3785.
Add support for Pattern. Extract Regex flags translation from Criteria into RegexFlags utility class. Add since and author tags. Simplify tests. Update reference documentation.
See #3725.
Original pull request: #3781.
Introduce factory methods to convert TimeZone/ZoneId/ZoneOffset into Mongo Timezone. Introduce TemporalUnit abstraction and converters to convert ChronoUnit and TimeUnit into TemporalUnit for date operators accepting a unit parameter.
See #3713
Original pull request: #3748.
Make fields final where possible. Update javadoc. Simplify assertions. Update reference docs.
See: #3715, See #3717, See #3727
Original pull request: #3741.
Add a SetWindowFieldsOperation to the aggregation framework.
The builder API allows fluent declaration of the aggregation stage as shown in the sample below.
SetWindowFieldsOperation.builder()
.partitionByField("state")
.sortBy(Sort.by(Direction.ASC, "date"))
.output(AccumulatorOperators.valueOf("qty").sum())
.within(Windows.documents().fromUnbounded().toCurrent().build())
.as("cumulativeQuantityForState")
.build();
Closes#3711
Original pull request: #3739.
Rename Granularities/Granularity to Granularity and GranularityDefinition to proivide a more natural wording towards using predefined granularities.
Validate presence of referenced properties through the TimeSeries annotation.
Tweak Javadoc, reformat code, add unit tests.
See #3731
Original pull request: #3732.
Along the lines make sure to convert map like structures correctly if they do not come as a Document, eg. cause they got converted to a plain Map in a post load, pre convert event.
Closes#3702
Original pull request: #3704.
This commit fixes a regression that prevented custom converters from being applied to types considered store native ones.
Original pull request: #3703.
Fixes#3670
Reformat code. Tweak javadoc. Reject wildcard projection usage on properties with a MappingException. Omit wildcard projections when declared on document types that are used as subdocument.
See #3225
Original pull request: #3671.
Move off our own Querydsl copies, as Querydsl 5.0 ships MongoDB Document API support.
Remove package-private duplicates of Querydsl code.
Introduce SpringDataMongodbQuerySupport to provide a well-formatted toString representation of the actual query.
Original Pull Request: #3674
While maps that have numeric keys work if there is only one map with an integer key, when there are multiple maps with numeric keys in a given query, it fails.
Take the following example for a map called outer with numeric keys holding reference to another object with a map called inner with numeric keys: Updates that are meant to generate {"$set": {"outerMap.1234.inner.5678": "hello"}} are instead generating {"$set": {"outerMap.1234.inner.inner": "hello"}}, repeating the later map property name instead of using the integer key value.
This commit adds unit tests both for the UpdateMapper and QueryMapper, which check multiple consecutive maps with numeric keys, and adds a fix in the KeyMapper. Because we cannot easily change the path parsing to somehow parse path parts corresponding to map keys differently, we address the issue in the KeyMapper. We keep track of the partial path corresponding to the current property and use it to skip adding the duplicated property name for the map to the query, and instead add the key.
This is a bit redundant in that we now have both an iterator and an index-based way of accessing the path parts, but it gets the tests passing and fixes the issue without making a large change to the current approach.
Fixes: #3688
Original Pull Request: #3689
The field projection conversion should actually only map field names and avoid value conversion. In the MongoId case an inclusion parameter (1) was unintentionally converted into its String representation which causes trouble on Mongo 4.4 servers.
Fixes: #3668
Original pull request: #3678.
Fix typo in class name and make sure MongoTestTemplate uses the configured simple types.
Remove superfluous junit extension.
See: #3659
Original pull request: #3661.
spring-projects/spring-data-commons#2293 changed how PersistentProperty paths get resolved and considers potentially registered converters for those, which made the path resolution fail in during the query mapping process.
This commit makes sure to capture the according exception and continue with the given user input.
Fixes: #3659
Original pull request: #3661.
This commit fixes an issue with the pattern used for detecting $or / $nor which also matched other keywords like $floor.
Closes: #3635
Original pull request: #3637.
Reorder methods and types. Rename MongoPersistentProperty.isOmitNullProperty to writeNullValues. Adapt caching MongoPersistentProperty and add tests.
Tweak Javadoc wording, add author and since tags.
See #3407
Original pull request: #3646.
Properties can be annotated with `@Field(write=…)` to control whether a property with a null value should be included or omitted (default) during conversion in the target Document.
Closes#3407
Original pull request: #3646.
Reduce dependencies in tests by using NoOpDbRefResolver.
Add since tags.
Tweak documentation. Extract entity references into own documentation fragment.
Original pull request: #3647.
Closes#3602.
Rename ReferenceReader to ReferenceLookupDelegate.
Rename LazyLoadingProxyGenerator to LazyLoadingProxyFactory.
Rename DefaultReferenceLoader to MongoDatabaseFactoryReferenceLoader.
Reduce scope of LookupFunction and move it to ReferenceLookupDelegate.
Extract some checks into methods to reflect the underlying concepts. Simplify code, convert variables to constants where possible.
Original pull request: #3647.
Closes#3602.
Simplify usage by computing the pointer from the lookup.
Update the reference documentation, add JavaDoc and refine API.
Original pull request: #3647.
Closes#3602.
Add initial support for an alternative to the existing DBRef scenario.
The enhancement allows to store and retrieve linked entites via their id or a customizable lookup query.
Original pull request: #3647.
Closes#3602.
DocumentCallback is now generally non-nullable for both, the input Document and the returned result expecting EntityReader to always return a non-null object.
Also, use try-with-resources where applicable.
Closes#3648
Let appendLimitAndOffsetIfPresent accept unary operators for adjusting limit/offset values instead of appendModifiedLimitAndOffsetIfPresent. Apply simple type extraction for Slice. Add support for aggregation result streaming.
Extend tests, add author tags, update docs.
See #3543.
Original pull request: #3645.
This commit fixes an issue where using a simple return type leads to NPE when the actual aggregation result does not contain any values.
Closes: #3623
Original pull request: #3625.
We now use StringUtils.replace(…) to replace the map key dot in MappingMongoConverter. StringUtils perform a plain search instead of using Regex which improves the overall performance.
Closes#3613
Omit StreamUtils usage if input is a collection. Remove superfluous Flux.from(…). Simplify test and migrate test to JUnit 5.
See #3609.
Original pull request: #3611.
Make SimpleReactiveMongoRepository#saveAll(Publisher<S>) return the saved entity references instead of the original references.
Closes#3609
Original pull request: #3611.
The meaning of embedding a Document in MongoDB is different compared to column based stores. Typically the term is used for a Document in Document approach and not for flattening out a values into the enclosing Document.
Closes: #3600
Original pull request: #3604.
Reorder methods. Tweak Javadoc and documentation wording. Mention projection expressions in the what's new section. Reformat code.
See #3583
Original pull request: #3585.
This commit makes sure to fall back to the configured custom converter if no more type specific converter has been registered.
Closes#3580
Original pull request: #3581.
We now only scan for entities annotated with `@Document` to avoid inclusion of non-MongoDB entities. Previously, types annotated (or meta-annotated) with `@Persistent` were included as MongoDB entity which could lead to mapping rule violations.
Closes#3592
Introduce a ConversionContext used during the mapping process to carry forward required information.
ConversionContext serves as entrpoint for recursive (read) conversion of documents, lists, maps, and simple values. The actual decision which converter strategy to apply is now encapsulated by ConversionContext.convert(…) which removes strategy duplications from the actual conversion methods.
Also, converter methods for documents, maps, lists, … are now protected for easier customization by subclasses.
Closes#3571
Original Pull Request: #3575
This commit makes sure to skip the class property ob Object when mapping maps and their keys inside an Update.
Closes#3566
Original pull request: #3577.
Reintroduce the protected ensureNotIterable method in MongoTemplate to keep the API stable. Delegate to the newly introduced method and move the collection like check to EntityOperations.
Original Pull Request: #590
Check if an object is an array or is an instance of collection or iterator instead of checking against collection names which is likely to never work.
Closes#2911
Original Pull Request: #590
We now consider the IgnoreCase part of a derived query when used along with In. Strings will be quoted to avoid malicious strings from being handed over to the server as a regular expression to evaluate.
See #3395
Original pull request: #3554.
This commit switches the rendering of UUID values to their toString format when printing org.bson.Document to json via the DocumentToString converter.
This will move the resulting representation from {"$binary": "QUK3ZihZ9cdhWjTf5TZqrw==", "$type": "03"} to 480971b0-7160-4120-acd0-6fd6b82418ad which is the more natural variant within Java applications.
The conversion only applies on read in cases where an entire document eg. a composite id, is mapped to a String property of the domain model.
Closes#3546.
Original pull request: #3551.
This commit makes sure to use an Encoder having UuidRepresentation set when calling org.bson.Document#toJson, preventing CodecConfigurationException from being raised.
Future versions will make sure the UUID string representation matches the Java default one.
Closes#3546.
Original pull request: #3551.
We now support embedded types in the sense of unwrapping nested objects into their parent Document to flatten out domain models where needed.
A domain class of:
public class User {
@Id
private String userId;
@Embedded(onEmpty = USE_NULL)
private UserName name;
}
public class UserName {
private String firstname;
private String lastname;
}
renders:
{
"_id" : "1da2ba06-3ba7",
"firstname" : "Emma",
"lastname" : "Frost"
}
Resolves#2803.
Original pull request: #896.
This commit reduces the visibility of the GeoJsonSerializersModule and instead offers static methods on GeoJsonModule allowing to obtain those via a static method.
The actual serialization was simpified by moving some of its code to a common base class.
Updated reference documentation - relates to: spring-projects/spring-data-commons#2288
We also did, by intent, not change the current GeoJsonModule to add the serializers by default in order to give users time to prepare for that change which will be done with the next major release.
Original pull request: #3539.
Closes#3517
By offering a getter method for the ReactiveMongoDatabaseFactory users subclassing ReactiveMongoTemplate could evaluate the current transaction state via ReactiveMongoDatabaseUtils.isTransactionActive(getDatabaseFactory()).
This change also aligns the reactive and imperative template implementation in that regard.
Closes#3540
Original pull request: #3541.
Align type variable naming with imperative extensions(I, O). Add extension without accepting KClass. Update since tags and tests.
See #3508.
Original pull request: #893.
Tweak wording in the docs. Remove unused code. Fix generics. Rename AggregateContext to AggregationOperation to AggregationDefinition to avoid yet another Context object.
See #3542.
Original pull request: #3545.
This commit switches from a strict to a relaxed type mapping for aggregation executions. This allows users to add fields to the aggregation that might be part of the stored document but not necessarily of its java model representation.
Instead of throwing an exception in those cases the relaxed type check will go on with the user provided field names.
To restore the original behaviour use the strictMapping() option on AggregationOptions.
Closes#3542
Original pull request: #3545.
Update Javadoc to reflect find and aggregation nature. Use primitive boolean on Query.allowDiskUse to avoid nullable type usage. Update ReactiveMongoTemplate to consider allowDiskUse.
Original pull request: #891.
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.
Avoid nullable method arguments and add assertions. Introduce build() method to AccumulatorFinalizeBuilder to build Accumulator without specifying a finalize function.
Original pull request: #887.
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.
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.
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.
Reorganize imports after Delomboking. Use for-loop instead of Stream.forEach(…). Add Javadoc to methods. Add since tags.
Simplify tests.
Original pull request: #761.
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.
Preinitialize EvaluationContextProvider with ReactiveQueryMethodEvaluationContextProvider to not require setting properties on vanilla ReactiveMongoRepositoryFactory objects.
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.
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
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.
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
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
We reenabled parameter binding within SpEL using query parameter placeholders ?0, ?1,... instead of their array index [0],[1],...
Original pull request: #864.
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.
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.
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.
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.
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
We improved the error message for unsupported return types instead of running into an IllegalArgumentException for unique results.
Original pull request: #851.
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.
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.
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.
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
We now include the documentations partial about custom conversions that explains default converter registrations, overrides and system setting timezone-sensitivity.
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.
Introduce support for SpEL aggregation expressions for AddFields and Set operations.
Rearrange methods. Make fields final where possible.
Original pull request: #801.
Migrate more tests to JUnit 5. Rearrange methods. Reduce method visibility according to JUnit 5 requirements.
Remove Java 11 build and only use Java 8 and 13.
Original pull request: #838.
Introduce Junit Jupiter extensions.
Flush collections instead of dropping them.
Apply cursor timeout to change stream and capped collections in tests.
Original pull request: #838.
Spring Data MongoDB uses the @Sharded annotation to identify entities stored in sharded collections.
The shard key consists of a single or multiple properties present in every document within the target collection, and is used to distribute them across shards.
Spring Data MongoDB will do best effort optimisations for sharded scenarios when using repositories by adding required shard key information, if not already present, to replaceOne filter queries when upserting entities. This may require an additional server round trip to determine the actual value of the current shard key.
By setting @Sharded(immutableKey = true) no attempt will be made to check if an entities shard key changed.
Please see the MongoDB Documentation for further details and the list below for which operations are eligible to auto include the shard key.
* Reactive/CrudRepository.save(...)
* Reactive/CrudRepository.saveAll(...)
* Reactive/MongoTemplate.save(...)
Original pull request: #833.
Adapt to changes in commons. Add functional create method to MongoCustomConversions. Update Javadoc and reference documentation. Truncate precision for Java 11 build compatibility in tests.
Original pull request: #810.
We now use the MongoDB Java driver InstantCodec instead of a dedicated converter. Other java.time types like LocalDate use a different zone offset when writing values which can lead to unexpected behavior. Therefore we added configuration options to MongoCustomConversions that allow to tell the conversion sub system which approach to use when writing those kind of types.
Original pull request: #810.
- Give the server a little time to think on ci system.
- Reuse and Close MongoClients in tests.
- Use WriteConcern majority in setup.
- Use longer transaction timeout on server
- Use junit-pioneer to repeatable tests known to fail due to network errors.
Original pull request: #831.
We now provide extensions for imperative and reactive distinct queries accepting Kotlin's KProperty and KProperty1 to express type-safe queries:
mongo.query<Customer>().distinct(Customer::name)
mongo.distinct(Customer::name)
Original Pull Request: #809
We now set the target type to org.bson.Document for id properties annotated with @Field having the implicit target type derived from the annotation. Along the lines we fixed warn message when an id property with explicit (unsupported) field name is detected.
Original pull request: #830.
@Meta(allowDiskUse...) allows to set the according aggregation option when executing a String based annotation via a repository definition.
Original pull request: #827.
Mono<Void> is now a supported return type of derived reactive deleteBy queries like:
Mono<Void> deleteByLastname(String lastname);
Original pull request: #825.
Move from AsyncInputStream handling to Publisher for GridFS.
UUID types require additional configuration setup to prevent errors while processing legacy (type 3) binary types. We still use type 3 as default but allow codec configuration for type 4 via Java and XML configuration.
Updated migration guide.
Original pull request: #823.
Replace leftovers to Mongo 2.x API with Document and MongoDatabase references and tweak Javadoc. Reorder field declarations to class header. Reflect 3.0 versions in schema configuration. Add TODO markers to disabled tests.
Reflect changes in documentation.
Enable disabled test.
Original pull request: #823.
This change switches to the MongoDB 4.0 driver and introduces configuration options for com.mongodb.client.MongoClient.
The XML namespace changed from client-options to client-settings and removed already deprecated elements and attributes.
Imports are switched from single artifact uber jar to split imports for driver-core, -sync and -reactivestreams.
Deprecations have been removed.
Original pull request: #823.
Previously we falsely converted the sort value (1/-1) into the id types target value when a Field annotation had been present.
Original pull request: #822.
In preparation for the upcoming breaking changes when switching to the MongoDB Java Driver 4.0 and the breaking changes required for that update (expected for Milestone 2), we eagerly bump the version number to 3.0.
Original pull request: #819.
We now preserve the collection nature of the source type when applying custom target type conversions. Prior to this change collection values had been changed to single element causing query errors in MongoDB when using $in queries.
Original pull request: #817.
Leverage `skip` and `limit` methods exposed in `GridFSFindIterable` to support limiting and skipping results.
In particular these changes allow the `find(Query)` method to correctly consider parameters of a page request.
Original pull request: #806.
MongoServerCondition replaces the JUnit 4 TestRules (MongoVersionRule & ReplicaSet) with a JUnit Jupiter ExecutionCondition.
Original Pull Request: #807
We now use a non-blocking state switch to determine whether to invoke drainLoop(…) from Subscriber completion.
Previously, we relied on same thread identification assuming if the subscription thread and the completion thread were the same, that we're already running inside the drain loop.
It turns out that a I/O thread could also run in event-loop mode where subscription and completion happens on the same thread but in between there's some processing and so the the call to completion is a delayed signal and not being called on the same stack as drainLoop(…).
The same-thread assumption was in place to avoid StackOverflow caused by infinite recursions.
We now use a state lock to enter the drain loop. Any concurrent attempts to re-enter the drain loop in Subscriber completion is now prevented to make sure that we continue draining while not causing stack recursions.
Original Pull Request: #807
Projections used within an aggregation pipeline can result in empty documents emitted by the driver. We now guarded those cases and skip those documents within a Flux or simply return an empty Mono depending on the methods signature.
Original pull request: #804.
AsyncInputStreamAdapter now properly splits and buffers incoming DataBuffers according the read requests of AsyncInputStream.read(…) calls.
Previously, the adapter used the input buffer size to be used as the output buffer size. A larger DataBuffer than the transfer buffer handed in through read(…) caused a BufferOverflow.
Original Pull Request: #799
We now rely on an outer drain-loop when GridFS reads complete on the same thread instead of using recursive subscriptions to avoid StackOverflow. Previously, we recursively invoked subscriptions that lead to an increased stack size.
Original Pull Request: #799
maxTimeMs defines the time limit for the aggregation operations. If not specified or set to zero, operations will not time out.
Original pull request: #800.
Execution time and test order changed by using JUnit5. This commit fixes some of the issues related to index creation where actually not needed.
Original pull request: #798.
This commit switches from simple collection.count(), operating on potentially false collection statistic, to countDocuments() using an aggregation for accurate results.
The transition required query modifications at some points because $match does not support $near and $nearSphere but require $geoWithin along with $center or $centerSphere which does not support $minDistance (see https://jira.mongodb.org/browse/SERVER-37043).
$geoWithin further more does not sort results by distance, but this fact can be ignored when just counting matches.
Examples:
{ location : { $near : [-73.99171, 40.738868], $maxDistance : 1.1 } }
{ location : { $geoWithin : { $center: [ [-73.99171, 40.738868], 1.1] } } }
{ location : { $near : [-73.99171, 40.738868], $minDistance : 0.1, $maxDistance : 1.1 } }
{$and :[ { $nor :[ { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 0.01] } } } ]}, { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 1.1] } } } ] }
Original pull request: #604.
Add author tags. Move integration tests to existing test class.
Apply more appropriate in existing tests assertions. Use diamond syntax.
Original pull request: #796.
We now consistently use GridFSFile.getId() to allow custom Id usage instead of enforcing the Id to be an ObjectId. Using the native Id allows interaction with files that use a custom Id type.
Original pull request: #796.
Internal field references to $$this and $$value are now no longer mapped against exposed fields which had caused errors before.
Original pull request: #792.
Exceptions during CursorReadingTask startup and during polling are handled now by the same exception handling to handle Exceptions only once and notify ErrorHandler exactly once per exception.
Previously, startup exceptions relied on exception handling in the execute closure and notified ErrorHandler potentially multiple times.
Original Pull Request: #790
We now consider native GeoJSON types of the MongoDB client during conversion passing on the raw values to the driver when writing and using the configured MongoDB codecs on read.
Original pull request: #786.
Same as with FindPublisherPreparer the CursorPreparer needs to be public because it is used in one of the protected methods of MongoTemplate.
Original Pull Request: #784
The FindPublisherPreparer is used in an protected method of ReactiveMongoTemplate and needs to be public to allow overriding.
Original Pull Request: #784
Since MongoDB 3.6 the slaveOk option translates to the primaryPreferred ReadPreference that is now again applied when executing a find operation.
Original pull request: #779.
We now check if the source is still the same object after potentially applying auditing modifications and make sure to pass the audited object on to the mapping layer.
Limited bean inspection scope of event listener tests to avoid side effects in index creation.
Original pull request: #780.
The MongoDB Java Driver does not handle java.time types. Therefore those must not be considered simple types.
The behavior was changed by DATACMNS-1294 forcing usage of Reading & WritingConverter annotations to disambiguate converter direction.
This commit restores the converter registration to the state before the change in Spring Data Commons.
Original pull request: #783.
To resolve XSD files properly from the classpath, their HTTPS reference must be present in the spring.schemas to avoid internet interaction for resolving an XSD file.
We now render field and local variable references correctly when using the $filter aggregation operator.
Prior to this commit field references had been rendered with an additional $ prefix.
Original pull request: #776.
This allows to obtain the raw Json representation of the query for eg. debug usage.
We also updated the toString method to return a full Mongo Shell compatible representation of the query including projections, order, skip and limit.
Original pull request: #774.
We now support Date to Long, Date to ObjectId, Script to String and other conversions for both reading and writing scenarios.
Original pull request: #773.
ErrorHandlers associated with a CursorReadingTask (Change Streams, imperative Tailable Cursors) now handle exceptions raised by the listener callback.
Exceptions are now catched and the callback continues with the next message.
MongoTemplate.stream(…), MongoTemplate.query(…) and ReactiveMongoTemplate.query(…) now no longer fail when used with BSON Document.class.
Previously, field mapping failed because it required an entity type. Now we gracefully back off when find methods are used with a simple Document entity type.
Add Nullable annotation to nullable method args. Remove IV from JSON Schema as it is not listed in Mongo specs.
Tweak wording in docs. Parse encryption-settings-ref for MongoClientOptions. Add support for KeyId's in encrypted JSON schema properties.
Original pull request: #766.
We now support encrypted fields via MongoJsonSchema and allow XML configuration of com.mongodb.AutoEncryptionSettings via a dedicated factory bean.
Original pull request: #766.
The $hint operator is deprecated since MongoDB 3.2 so we're now deprecating Query.withHint() accepting a String as the String is expected to be a valid document. Therefore, we're introducing withHint(Document) to accept a type-safe representation of query hints.
Reduce AtTest(expected = …) and ExpectedException with the corresponding AssertJ assertThatExceptionOfType(…) and assertThatIllegalArgumentException().isThrownBy(…).
We now configure resolved text-indexes with a simple collation when the text index is created in a collection that uses a non-simple collation.
This explicit setting is required by MongoDB to properly create a text index.
Previously, index creation failed.
This fix allows using alike on nested properties.
new Criteria("nested").alike(Example.of(probe, matching().withIgnorePaths("_class"))));
Switch tests to AssertJ.
Original pull request: #771.
We now offer a fluent API for more intuitive change stream interaction.
Flux<ChangeStreamEvent<User>> flux = reactiveTemplate.changeStream(User.class)
.watchCollection("people")
.filter(where("age").gte(38))
.listen();
Original pull request: #751.
Tweak Javadoc. Simplify Fields creation from Stream. Remove final modifier from private static method. Iterate with loop over PersistentEntity.
Original pull request: #748.
Use the mapping context to get the required fields or fall back to property descriptors if no mapping context is available.
Original pull request: #748.
We now allow to derive field names for a $project stage from a given type by including all top level fields.
// $project : { title : 1, author : 1 }
Aggregation.project(Book.class)
Original pull request: #748.
Use getCollectionName() in MongoTemplate.insert/save. Consistently use getCollectionName(Class) from ReactiveMongoTemplate and fluent API implementations.
Original pull request: #768.
Tested against 4.0.9 and 4.2.0-rc1 servers.
Added a delay and left a todo in one of the tests where the 4.2.0-rc1 server takes a bit longer than it predecessor when creating indexes which can lead to BackgroundOperationInProgressForNamespace errors.
Original pull request: #764.
Use the reworked version of the EntityCallback method lookup.
Also fix issues with callbacks not invoked when intended and rework the reactive flow by removing deeply nested constructs.
Update documentation and add EntityCallbacks to BulkOperations.
Original Pull Request: #742
We now use EntityCallback to invoke callback actions on entities before saving/before conversion to provide hooks that potentially modify an entity before persisting it.
We also provide a reactive variant of entity callbacks allowing to consume Reactor Context and to defer the actual activity.
Original Pull Request: #742
Current MongoAnnotationProcessor still uses 3.x.x Querydsl package names.
Update package names to com.querydsl.core.annotations.* to use Querydsl annotations for code-generation.
Original pull request: #755.
We now support hashed index definitions via IndexOperations. Reading index information back allows to identify a hashed index via isHashed().
Original pull request: #750.
OutOperation now supports the expanded format for the $out aggregation operation if additional parameters, next to the target collection, are given.
Aggregation.out("out-col").insertDocuments().in("database-2").uniqueKey("field-1“);
{
$out : {
to : "out-col",
mode : "insertDocuments",
db : "database-2",
uniqueKey : "field-1"
}
}
We’ll stick to the 2.6 format if only a collection name has been set.
Aggregation.out("out-col“);
{ $out : "out-col" }
Original pull request: #740.
We now make sure to call the delegate AggregationOperationContext without potentially overriding arguments. Without this change potentially registered target types would be overridden with null.
We now apply propagate the cursor size to aggregation options. We introduced AggregationOptions.comment to propagate the meta comment to aggregation execution.
Original pull request: #743.
Use MongoQueryMethod.getDomainClass() instead of getRepositoryDomainType(). Simplify annotation presence indicator methods hasAnnotatedSort() and hasAnnotatedCollation(). Refactor getAnnotatedAggregation() to non-nullable method throwing IllegalStateException to be consistent with other getXxx() methods.
Simplify aggregation execution and consider collection/single element declaration for reactive execution.
Tweak docs.
Original pull request: #743.
Reuse collection name for index creation instead of resolving the collection for every index. Switch lambda to method reference.
Original pull request: #746.
We now lazily read the collection of an entity as it potentially requires a more expensive SpEL evaluation that might not have been required in fist place.
Original pull request: #746.
Fix count operation inside transaction and avoid superfluous client session instantiation.
Default MongoDatabase emission in case of non active transaction, update documentation, move test to another package.
Delay reactive collection re/creation in test to cope with issues in server version 4.1.10.
Original Pull Request: #745
Support declarative reactive transaction via the Transactional annotation via a MongoDB specific ReactiveTransactionManager implementation.
@Bean
ReactiveMongoTransactionManager transactionManager(ReactiveDatabaseFactory factory) {
return new ReactiveMongoTransactionManager(factory);
}
@Component
public class StateService {
@Transactional
Mono<UpdateResult> someBusinessFunction(Step step) {
return template.insert(step)
.then(process(step))
.then(template.update(Step.class).apply(Update.set("state", …));
};
});
Original Pull Request: #745
Store result to getPersistentEntity() in local variable to reduce invocation count. Use numbered postfix instead of object instantiation to generate a unique distance field name.
Deprecate geoNear methods with hint to aggregations. Fix distance field usage in ReactiveMongoTemplate.
Tweak docs.
Original pull request: #744.
Deprecate and guard tests for removed commands:
- eval
- group
- maxScan
- geoNear
Transition from removed geoNear command to $geoNear aggregation pipeline stage.
This allows users to still use NearQuery along with the template that now transforms the query into a GeoNearOperation applying skip (previously in memory skipping) and limit (previous num parameter) as additional aggregation pipeline stages.
Tested against:
- 4.1.10
- 4.0.4
- 3.6.12
- 4.4.20
Original pull request: #744.
The collation can now also be configured on entity level and gets applied via MongoTemplate. However one can alway override a default collation by adding the collation explicitly to either the Query or one of the Options available for various operations.
When it comes to the repository level the hierarchy is method parameter over query annotation over entity metadata.
Remove collation annotation in favor of attributes of Query / Document.
Original pull request: #644.
We now allow to specify the collation via the @Query annotation.
public interface PersonRepository extends MongoRepository<Person, String> {
@Query(collation = "en_US")
List<Person> findByFirstname(String firstname);
@Query(collation = "{ 'locale' : 'en_US' }")
List<Person> findPersonByFirstname(String firstname);
@Query(collation = "?1")
List<Person> findByFirstname(String firstname, Object collation);
@Query(collation = "{ 'locale' : '?1' }")
List<Person> findByFirstname(String firstname, String collation);
List<Person> findByFirstname(String firstname, Collation collation);
}
We now make sure to include collation information derived from the Query method if the collation is a fixed value.
Original pull request: #644.
Align Indexed(expireAfter) default to empty string according to the documentation. Slightly reword Javadoc.
Import DurationStyle to reuse duration parsing until Spring Framework provides a similar utility. Document ISO-8601 duration style. Prevent null index name evaluation to render "null" as String.
Convert assertions from Hamcrest to AssertJ.
Original pull request: #647.
We now also evaluate SpEL expressions for the name of indices as well as the def attribute of the compound index definition.
@CompoundIndex(name = "#{'cmp' + 2 + 'name‘}“, def = "#{T(org.bson.Document).parse(\"{ 'foo': 1, 'bar': -1 }\")}")
class WithCompoundIndexFromExpression {
// …
}
An expression used for Indexed.expireAfter may now not only return a plain String value with the timeout but also a java.time.Duration.
Original pull request: #647.
We added expireAfter which accepts numeric values followed by the unit of measure (d(ays), h(ours), m(inutes), s(econds)) or a Spring template expression to the Indexed annotation.
@Indexed(expireAfter = "10s")
String expireAfterTenSeconds;
@Indexed(expireAfter = "1d")
String expireAfterOneDay;
@Indexed(expireAfter = "#{@mySpringBean.timeout}")
String expireAfterTimeoutObtainedFromSpringBean;
Original pull request: #647.
Fix generics usage in MappingMongoJsonSchemaCreator. Make fields final. Rename MappingMongoConverter.computeWriteTarget to getWriteTarget and expose it publicly for reuse in custom DefaultTypeMapper setups without the need to subclass MappingMongoConverter.
Remove Nullability functionality for required fields as nullability indicators should originate from PersistentProperty and PreferredConstructor. Update documentation.
Related ticket: DATACMNS-1513
Original pull request: #733.
MongoJsonSchemaCreator extracts the MongoJsonSchema for a given Class by applying the following mapping rules:
Required Properties:
- Properties of primitive type.
Ignored Properties:
- All properties annotated with Transient.
Property Type Mapping:
- java.lang.Object -> { type : 'object' }
- java.util.Arrays -> { type : 'array' }
- java.util.Collection -> { type : 'array'}
- java.util.Map -> { type : 'object'}
- java.lang.Enum -> { type : 'string', enum : [ ... ] }
- Simple Types -> { type : 'the corresponding bson type' }
- Domain Types -> { type : 'object', properties : { ... } }
_id properties using types that can be converted into
ObjectId like String will be mapped to { type : 'object' } unless there is more specific information available via the MongoId annotation.
By using Field#targetType it is now possible to pass down a type hint to the conversion subsystem. This allows specifying the desired target type for a property so that eg. a plain String can be stored as Code.
Original pull request: #733.
We now pass on the range defined by Query.skip and Query.limit to MongoDB. This allows to count documents within a certain range so that it is possible to find the number of matches within eg. the first 10,000 documents.
Original pull request: #650.
We now reuse the MongoConverter instance that is associated with a MongoTemplate when using withSession(…) instead of creating a new converter instance.
In consequence, we're reusing PersistentEntity instances, EntityInstantiators and generated accessor classes.
Original Pull Request: #734
We now make sure we to not convert Strings representing valid ObjectIds into the such for paths that cannot be resolved to a Property.
Original pull request: #732.
We added trace logging to DefaultDbRefResolver.
<logger name="org.springframework.data.mongodb.core.convert.DefaultDbRefResolver" level="trace"/>
Original pull request: #659.
We now decrement the demand and propagate exceptions from the adapter. Previously, we did not decrement the demand and kept emitting buffers although the subscriber demand was satisfied.
Original Pull Request: #693
ReactiveMongoTemplate.findAllAndRemove(…) now completes successfully without emitting a result if the find query yields no hits. We no longer call the subsequent remove query if without previous results.
Original Pull Request: #657
Update Javadoc to reflect that array filters are used in their raw form without domain-type related type- or field mapping.
Original pull request: #656.
We now support filtered positional $[<identifier>] operator via Updates. This allows to specify a filter criteria chain for the elements in an array.
new Update()
.set("grades.$[element]", 100)
.filterArray(Criteria.where("element").gte(100));
Array filters can be used for MongoOperations#update* & MongoOperations#findAndModify
Original pull request: #656.
We now parse String arguments bound to an $oid correctly, so that those end up as valid ObjectId.
@Query("{ 'arg0' : { '$oid' : ?0} }")
List<Person> singeObjectIdArgInQueryString(String arg0);
Original pull request: #652.
Add tests for aggregation using GeoJsonPoint. Extract GeoJson checks in own methods. Update license headers. Extract multiplier conversion in MetricConversion. Fix distanceMultiplier calculation to TargetUnit/BaseUnit instead of BaseUnit/TargetUnit.
Original pull request: #339.
We now convert GeoJsonPoint used in NearQuery into its according format. This also requires to convert any given min/maxDistance as well as the distanceMultiplier into meters (metric system).
Along the way we fixed an issue where the actual Query used along with NearQuery was not properly mapped to the domain types properties.
Original pull request: #339.
We promote the usage of reified Kotlin API usage (myMethod<Person>() instead of myMethod(Person::class)) to facilitate a single and more idiomatic approach to Kotlin API usage.
Extension methods accepting KClass are deprecated now.
Original Pull Request: #648
This commit introduces Coroutines support for
ReactiveFluentMongoOperations API via Kotlin extensions that provide
suspendable functions prefixed by `await` or suffixed by `AndAwait` for
Mono based APIs.
Extensions for Flux will be added when Kotlin/kotlinx.coroutines#254
will be fixed.
Original pull request: #649.
We now support o.s.d.domain.Range as method parameter for between queries. This allows more fine grained control over the inclusion/exclusion of the upper/lower bounds. Up till now between required 2 parameters which had been strictly bound to excluding bounds using $gt and $lt.
Original pull request: #645.
We now no longer register a MongoMappingContext bean when using @EnableMongoRepositories. Previously, we attempted to find a MongoMappingContext bean by name and if there was no such bean, we registered a new one. Additionally, the MappingContext was registered without considering SimpleTypes.
Bean discovery using aImportBeanDefinitionRegistrar is error-prone due to its ordering and timing nature because there is no guarantee that all beans are already registered.
Original Pull Request: #642
Align copyright years with forked code. Add customization markers to identify code blocks that were altered (in comparison to the original code) for future fork updates.
Original pull request: #643.
We moved in and adapted some classes from the MongoDB Java driver in order to bind parameters to placeholders while parsing a JSON string. This allows us to move off the deprecated JSON.parse method that will be removed with the 4.0 version of the driver.
Original pull request: #643.
Fix those deprecations with alternatives available. Some still have to remain in code as it is unclear which API to use with the 4.x driver.
Leave some TODOs in the code to find those spots when upgrading to the 4.0 MongoDB Java Driver.
Original pull request: #643.
OptimisticLockingFailureException is now thrown only when deleting an entity through a repository and no longer when using the Template API.
Original pull request: #641.
We now consider a potential @Version when removing an entity.
MongoOperations#remove(Object) and MongoOperations#remove(Object, String) include the version of the object to remove if the entity is versioned. Opposed to save(Object), remove(Object) does not throw OptimisticLockingFailureException if a versioned entity could not be removed. This behavior is subject to be changed in a future release. Throwing OptimisticLockingFailureException on failed delete on Template API level was not introduced to not break existing application code.
MongoRepository now also considers the entities version, following the very same logic as MongoOperations.
To remove an entity without version check use MongoOperations#remove(Query,…) or MongoRepository#deleteById(…).
Original pull request: #641.
We now support reactive GridFS using MongoDB's reactive GridFS API. Files can be consumed and provided as binary stream.
ReactiveGridFsOperations operations = …;
Publisher<DataBuffer> buffers = …
Mono<ObjectId> id = operations.store(buffers, "foo.xml");
Flux<DataBuffer> download = operations.getResource("foo.xml").flatMap(ReactiveGridFsResource::getDownloadStream);
Original Pull Request: #637
ReactiveMongoTemplate.insert(…) now uses the saved entity when emitting AfterSaveEvent. This change affects usage of immutable objects that are using Id generation. Previously, the to-be-saved entity instance was used which left the Id unpopulated.
Original Pull Request: #638
Introduce base class for common Querydsl query execution tasks that can be used for imperative and reactive implementation.
Fix test issues due to context caching where indices are not recreated when dropping the collection during test setup.
Update reference documentation.
Original Pull Request: #635
We now support execution of Querydsl Predicates using reactive MongoDB repositories. Reactive repositories are only required to add ReactiveQuerydslPredicateExecutor to their declaration to enable Querydsl.
public interface PersonRepository extends ReactiveMongoRepository<Person, String>, ReactiveQuerydslPredicateExecutor<Person> {
// additional query methods go here
}
PersonRepository repository = …;
QPerson person = new QPerson("person");
Flux<Person> result = repository.findAll(person.address.zipCode.eq("C0123"));
Original Pull Request: #635
Undo deprecation and transition to configuration option allowing to disable the index creation. Index creation will remain in the codebase as it is used in a lot of places to configure required geo index structures in MongoDB without which query execution would fail.
Original Pull Request: #636
We now provide IndexResolver to resolve and derive index definitions from Mongo entities.
MongoMappingContext mappingContext = new MongoMappingContext();
IndexResolver indexResolver = IndexResolver.create(mappingContext);
Iterable<? extends IndexDefinitionHolder> definitions = indexResolver.resolveIndexFor(MyEntity.class);
Original Pull Request: #636
Auto-index creation can now be disabled by setting MongoMappingContext.setAutoIndexCreation(false). This configuration prevents automatic index creation on application startup and during access to entities.
Original Pull Request: #636
MetadataBackedField no longer fails when Path detects reference to field within java.lang.Class. This can happen when splitting the property name via camel case where the first part matches to class which resolves to the getClass() call on java.lang.Object. When then the 2nd part also maps to a method (like getName()) on Class an error would be thrown.
Original Pull Request: #631
QueryMapper now excludes the type key in during mapping and retains the value as-is. This change fixes an issue in which type keys were attempted to be mapped using the entity model. Type key resolution for _class failed silently while other type keys such as className failed in property path resolution and the failure became visible.
Original Pull Request: #631
We now make sure that mapped updates (as in doSaveVersioned and doUpdate) are mapped only once as mapping is required only once. Mapping already mapped query/update objects comes with undesired side-effects such as following invalid property paths or reduction of type information availability.
We now make sure to map key/value pairs of Map like properties to the values domain type, and apply potentially registered custom converters to the keys.
Fixed invalid test for DATAMONGO-1423 as this one did not check the application of the registered converter.
Original pull request: #625.
Set interrupted thread state after catching InterruptedException. Fix potential NPE by checking the cursor. Streamline generics to not hide class-level generic types.
Original pull request: #634.
We now make sure to translate and pass on errors during the cursor initialization procedure to the configured error handler.
Original pull request: #634.
MetadataBackedField.getPath() now returns null instead throwing an error for fields that are not part of the domain model. This allows adding any field when updating an entity.
Original pull request: #633.
The previous implementation of (Reactive)MongoTemplate.doInsertBatch(…) prematurely initialized the version property so that the entity wasn't considered new by the auditing subsystem. Even worse, for primitive version properties, the initialization kept the property at a value of 0, so that the just persisted entity was still considered new. This mean that via the repository route, inserts are triggered even for subsequent attempts to save an entity which caused duplicate key exceptions.
We now make sure we fire the BeforeConvertEvent before the version property is initialized or updated. Also, the initialization of the property now sets primitive properties to 1 initially.
Related tickets: DATAMONGO-2139, DATAMONGO-2150.
Original Pull Request: #632
We now consider the collection name that is bound to the repository when inserting entities of which all are new. Previously, the collection name was derived from the entity.
Original Pull Request: #632
Use ObjectUtils to compote hash code as hash code implementation contained artifacts that do not belong there. Extract test method.
Original pull request: #629.
We now return null instead of an empty string when calling IndexInfo#getPartialFilterExpression. The method has been marked to return null vales before and we’re complying to that contract and return value expectation.
Original pull request: #629.
Rename NestedProperty to KPropertyPath to reflect the underlying concept in alignment with our own PropertyPath type. Rename nestedFieldName(…) method to asString(…) to align with Kotlin method terminology. Reformat.
Slightly reword documentation. Add Type-safe Queries for Kotlin to What's New section.
Original pull request: #622.
We now support type-safe queries using Kotlin's DSL capabilities by accepting property references. Property references map to property paths and are translated to Criteria objects.
mongoOperations.find<Book>(
Query(Book::title isEqualTo "Moby-Dick")
)
mongoOperations.find<Book>(
Query(Book::title exists true)
)
mongoOperations.find<Book>(
Query(Criteria().andOperator(
Book::price gt 5,
Book::price lt 10)
))
Original pull request: #622.
Fix imperative auditing test to use intended persist mechanism. Remove final keywords from method args and local variables in ReactiveMongoTemplate. Rename DBObject to Document.
Original Pull Request: #627
The previous implementation of ReactiveMongoTemplate.doSaveVersioned(…) prematurely initialized the version property so that the entity wasn't considered new by the auditing subsystem. Even worse, for primitive version properties, the initialization kept the property at a value of 0, so that the just persisted entity was still considered new. This mean that via the repository route, inserts are triggered even for subsequent attempts to save an entity which caused duplicate key exceptions.
We now make sure we fire the BeforeConvertEvent before the version property is initialized or updated. Also, the initialization of the property now sets primitive properties to 1 initially.
Added integration tests for the auditing via ReactiveMongoTemplate and repositories.
Related ticket: DATAMONGO-2139.
Original Pull Request: #627
We now no longer use DatatypeConverter to convert byte[] to its Base64-representation but use Spring Framework's Base64 utils.
Original pull request: #626.
Add ticket reference to follow-up ticket regarding array matching on partial DBRef expressions.
Related ticket: DATAMONGO-2154
Original pull request: #623.
The previous implementation of MongoTemplate.doSaveVersioned(…) prematurely initialized the version property so that the entity wasn't considered new by the auditing subsystem. Even worse, for primitive version properties, the initialization kept the property at a value of 0, so that the just persisted entity was still considered new. This mean that via the repository route, inserts are triggered even for subsequent attempts to save an entity which caused duplicate key exceptions.
We now make sure we fire the BeforeConvertEvent before the version property is initialized or updated. Also, the initialization of the property now sets primitive properties to 1 initially.
Added integration tests for the auditing via MongoOperations and repositories.
We now defensively create a List rather than a LinkedHashSet (which Spring's CollectionFactory.createCollection(…) defaults to) to make sure we're not accidentally dropping values that are considered equal according to their Java class definition.
Replace duplicate checks to ClientSession.hasActiveTransaction() with MongoResourceHolder.hasActiveTransaction(). Introduce MongoResourceHolder.getRequiredSession() to avoid nullability warnings.
Original pull request: #618.
Introduce FieldType to express the desired field type to use for MongoDB Id conversion. Adapt Querydsl Id conversion so Id values are converted in the QueryMapper and no longer in SpringDataMongodbSerializer.
Adapt tests. Move MongoId from o.s.d.mongodb to o.s.d.m.c.core. Javadoc, reference docs.
Original pull request: #617.
@MongoId allows more fine grained control over id conversion by specifying the intended id target type. This allows to skip the automatic to ObjectId conversion of values that happen to be valid ObjectId hex strings.
public class PlainStringId {
@MongoId String id; // treated as String no matter what
}
public class PlainObjectId {
@MongoId ObjectId id; // treated as ObjectId
}
public class StringToObjectId {
@MongoId(FieldType.OBJECT_ID) String id; // treated as ObjectId if the value is a valid ObjectId hex string
}
Original pull request: #617.
Add fix for bound reified type in fluent MapReduce operations.
Also add missing reified type extension to FindDistinct with projection.
Original Pull Request: #609
We now fixed Kotlin extension generics to properly use projections by ignoring the source type of the Fluent API object. Previously, the source and target type were linked which prevented the use of a different result type.
Original Pull Request: #609
Using the fluent API allows using DTO projections with properties that are unknown to the actual domain object. Previously, DTO projections attempted to read the domain type and during property access, missing properties were reported with an IllegalArgumentException. Unknown properties remain now unset.
Original Pull Request: #608
We now support queries to return a tailable cursor using the fluent reactive API.
query(Human.class)
.inCollection("star-wars")
.as(Jedi.class)
.matching(query(where("firstname").is("luke")))
.tail();
Original Pull Request: #608
Move and enhance tailable cursor documetation. Move to separate file, preserve anchor and add imperative way using a MessageListener.
Add additional notes on usage of com.mongodb.client.MongoClient.
Original pull request: #607.
We now redeclare the Asciidoctor Maven plugin to register the store specific attributes. Apparently they must not contain dots, so we replaced them with dashes.
Tweak Javadoc. Surpress generics warnings. Remove nullable annotation from ObjectOperatorFactory.value as it cannot be null. Extend tests. Reformat.
Original pull request: #601.
In MappingMongoConverter, we now avoid the creation of a ParameterValueProvider for parameter-less constructors. We also skip property population if entity can be constructed entirely through constructor creation. Replaced the lambda in MappingMongoConverter.readAndPopulateIdentifier(…) with direct call to ….readIdValue(…). Objectpath now uses decomposed ObjectPathItems to avoid array copying and creation. It now stores a reference to its parent and ObjectPathItem fields are now merged into ObjectPath, which reduces the number of created objects during reads.
Extended CachingMongoPersistentProperty with DBRef caching. Turned key access in DocumentAccessor into an optimistic lookup. DbRefResolverCallbacks are now created lazily.
Related tickets: DATACMNS-1366.
Original pull request: #602.
We now support the following type conversion aggregation operators:
* $convert
* $toBool
* $toDate
* $toDecimal
* $toDouble
* $toInt
* $toLong
* $toObjectId
* $toString
Original pull request: #595.
Return false instead of null in isTransactionFailureCode(…)/isClientSessionFailureCode(…) to prevent null-dereference. Add initial size to HashMap instances with known number of elements. Fix typos in private constant names. Fix duplicate error code ids.
Original pull request: #592.
Use getRequiredPersistentEntity() instead of getPersistentEntity() for improved null-safety. Use Lombok to for required args constructors. Slightly tweak Javadoc.
Original pull request: #591.
Remove duplicate tests and fix assertions on existing ones. Move tests over to AssertJ and fix output database not applied correctly.
Original Pull Request: #588
We now consider the output type (collection output) when rendering the MapReduce command. Previously, all output was returned inline without storing the results in the configured collection.
Original Pull Request: #588
- [ ] You have read the [Spring Data contribution guidelines](https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc).
- [ ] There is a ticket in the bug tracker for the project in our [JIRA](https://jira.spring.io/browse/DATAMONGO).
- [ ] You use the code formatters provided [here](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide) and have them applied to your changes. Don’t submit any formatting related changes.
- [ ] You submit test cases (unit or integration tests) that back your changes.
- [ ] You added yourself as author in the headers of the classes you touched. Amend the date range in the Apache license header if needed. For new types, add the license header (copy from another file and set the current year only).
- 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
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 http://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at http://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/].
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc[here].
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/main/CONTRIBUTING.adoc[here].
image:https://spring.io/badges/spring-data-mongodb/ga.svg[Spring Data MongoDB,link=https://spring.io/projects/spring-data-mongodb#quick-start] image:https://spring.io/badges/spring-data-mongodb/snapshot.svg[Spring Data MongoDB,link=https://spring.io/projects/spring-data-mongodb#quick-start]
= Spring Data MongoDB image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2Fmain&subject=Build[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/] https://gitter.im/spring-projects/spring-data[image:https://badges.gitter.im/spring-projects/spring-data.svg[Gitter]]
The primary goal of the https://spring.io/projects/spring-data[Spring Data] project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services.
The Spring Data MongoDB project aims to provide a familiar and consistent Spring-based programming model for new datastores while retaining store-specific features and capabilities.
The Spring Data MongoDB project provides integration with the MongoDB document database.
Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB `+Document+` and easily writing a repository style data access layer.
[[code-of-conduct]]
== Code of Conduct
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]]
== Getting Started
Here is a quick teaser of an application using Spring Data Repositories in Java:
[source,java]
----
public interface PersonRepository extends CrudRepository<Person, Long> {
class ApplicationConfig extends AbstractMongoClientConfiguration {
@Override
protected String getDatabaseName() {
return "springdata";
}
}
----
[[maven-configuration]]
=== Maven configuration
Add the Maven dependency:
[source,xml]
----
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}</version>
</dependency>
----
If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository
and declare the appropriate dependency version.
[source,xml]
----
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}-SNAPSHOT</version>
</dependency>
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
----
[[upgrading]]
== Upgrading
Instructions for how to upgrade from earlier versions of Spring Data are provided on the project https://github.com/spring-projects/spring-data-commons/wiki[wiki].
Follow the links in the https://github.com/spring-projects/spring-data-commons/wiki#release-notes[release notes section] to find the version that you want to upgrade to.
[[getting-help]]
== Getting Help
Having trouble with Spring Data? We’d love to help!
* Check the
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/[reference documentation], and https://docs.spring.io/spring-data/mongodb/docs/current/api/[Javadocs].
* Learn the Spring basics – Spring Data builds on Spring Framework, check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
If you are just starting out with Spring, try one of the https://spring.io/guides[guides].
* If you are upgrading, check out the https://docs.spring.io/spring-data/mongodb/docs/current/changelog.txt[changelog] for "`new and noteworthy`" features.
* Ask a question - we monitor https://stackoverflow.com[stackoverflow.com] for questions tagged with https://stackoverflow.com/tags/spring-data[`spring-data-mongodb`].
You can also chat with the community on https://gitter.im/spring-projects/spring-data[Gitter].
* Report bugs with Spring Data MongoDB at https://github.com/spring-projects/spring-data-mongodb/issues[github.com/spring-projects/spring-data-mongodb/issues].
[[reporting-issues]]
== Reporting Issues
Spring Data uses Github as issue tracking system to record bugs and feature requests.
If you want to raise an issue, please follow the recommendations below:
* Before you log a bug, please search the https://github.com/spring-projects/spring-data-mongodb/issues[issue tracker] to see if someone has already reported the problem.
* If the issue does not already exist, https://github.com/spring-projects/spring-data-mongodb/issues/new[create a new issue].
* Please provide as much information as possible with the issue report, we like to know the version of Spring Data that you are using, the JVM version, Stacktrace, etc.
* If you need to paste code, or include a stack trace use https://guides.github.com/features/mastering-markdown/[Markdown] code fences +++```+++.
[[guides]]
== Guides
The https://spring.io/[spring.io] site contains several guides that show how to use Spring Data step-by-step:
* https://spring.io/guides/gs/accessing-data-mongodb/[Accessing Data with MongoDB] is a very basic guide that shows you how to create a simple application and how to access data using repositories.
* https://spring.io/guides/gs/accessing-mongodb-data-rest/[Accessing MongoDB Data with REST] is a guide to creating a REST web service exposing data stored in MongoDB through repositories.
[[examples]]
== Examples
* https://github.com/spring-projects/spring-data-examples/[Spring Data Examples] contains example projects that explain specific features in more detail.
[[building-from-source]]
== Building from Source
You do not need to build from source to use Spring Data. Binaries are available in https://repo.spring.io[repo.spring.io]
and accessible from Maven using the Maven configuration noted <<maven-configuration,above>>.
NOTE: Configuration for Gradle is similar to Maven.
The best way to get started is by creating a Spring Boot project using MongoDB on https://start.spring.io[start.spring.io].
Follow this https://start.spring.io/#type=maven-project&language=java&platformVersion=3.0.0&packaging=jar&jvmVersion=17&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=data-mongodb[link]
to build an imperative application and this https://start.spring.io/#type=maven-project&language=java&platformVersion=3.0.0&packaging=jar&jvmVersion=17&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=data-mongodb-reactive[link]
to build a reactive one.
However, if you want to try out the latest and greatest, Spring Data MongoDB can be easily built with the https://github.com/takari/maven-wrapper[Maven wrapper]
and minimally, JDK 17 (https://www.oracle.com/java/technologies/downloads/[JDK downloads]).
In order to build Spring Data MongoDB, you will need to https://www.mongodb.com/try/download/community[download]
and https://docs.mongodb.com/manual/installation/[install a MongoDB distribution].
Once you have installed MongoDB, you need to start a MongoDB server. It is convenient to set an environment variable to
your MongoDB installation directory (e.g. `MONGODB_HOME`).
To run the full test suite, a https://docs.mongodb.com/manual/tutorial/deploy-replica-set/[MongoDB Replica Set]
is required.
To run the MongoDB server enter the following command from a command-line:
[](http://projects.spring.io/spring-data-mongodb#quick-start)
[](http://projects.spring.io/spring-data-mongodb#quick-start)
# Spring Data MongoDB
The primary goal of the [Spring Data](http://projects.spring.io/spring-data) project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services.
The Spring Data MongoDB project aims to provide a familiar and consistent Spring-based programming model for new datastores while retaining store-specific features and capabilities. The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a repository style data access layer.
## Getting Help
For a comprehensive treatment of all the Spring Data MongoDB features, please refer to:
* the [User Guide](http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/)
* the [JavaDocs](http://docs.spring.io/spring-data/mongodb/docs/current/api/) have extensive comments in them as well.
* the home page of [Spring Data MongoDB](http://projects.spring.io/spring-data-mongodb) contains links to articles and other resources.
* for more detailed questions, use [Spring Data Mongodb on Stackoverflow](http://stackoverflow.com/questions/tagged/spring-data-mongodb).
If you are new to Spring as well as to Spring Data, look for information about [Spring projects](http://projects.spring.io/).
## Quick Start
### Maven configuration
Add the Maven dependency:
```xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}.RELEASE</version>
</dependency>
```
If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.
```xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}.BUILD-SNAPSHOT</version>
</dependency>
<repository>
<id>spring-libs-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>http://repo.spring.io/libs-snapshot</url>
</repository>
```
### MongoTemplate
MongoTemplate is the central support class for Mongo database operations. It provides:
* Basic POJO mapping support to and from BSON
* Convenience methods to interact with the store (insert object, update objects) and MongoDB specific ones (geo-spatial operations, upserts, map-reduce etc.)
* Connection affinity callback
* Exception translation into Spring's [technology agnostic DAO exception hierarchy](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/dao.html#dao-exceptions).
### Spring Data repositories
To simplify the creation of data repositories Spring Data MongoDB provides a generic repository programming model. It will automatically create a repository proxy for you that adds implementations of finder methods you specify on an interface.
For example, given a `Person` class with first and last name properties, a `PersonRepository` interface that can query for `Person` by last name and when the first name matches a like expression is shown below:
The queries issued on execution will be derived from the method name. Extending `CrudRepository` causes CRUD methods being pulled into the interface so that you can easily save and find single entities and collections of them.
You can have Spring automatically create a proxy for the interface by using the following JavaConfig:
This sets up a connection to a local MongoDB instance and enables the detection of Spring Data repositories (through `@EnableMongoRepositories`). The same configuration would look like this in XML:
Here are some ways for you to get involved in the community:
* Get involved with the Spring community on Stackoverflow and help out on the [spring-data-mongodb](http://stackoverflow.com/questions/tagged/spring-data-mongodb) tag by responding to questions and joining the debate.
* Create [JIRA](https://jira.spring.io/browse/DATAMONGO) tickets for bugs and new features and comment and vote on the ones that you are interested in.
* Github is for social coding: if you want to write code, we encourage contributions through pull requests from [forks of this repository](http://help.github.com/forking/). If you want to contribute code this way, please reference a JIRA ticket as well covering the specific issue you are addressing.
* Watch for upcoming articles on Spring by [subscribing](http://spring.io/blog) to spring.io.
Before we accept a non-trivial patch or pull request we will need you to [sign the Contributor License Agreement](https://cla.pivotal.io/sign/spring). Signing the contributor’s agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. If you forget to do so, you'll be reminded when you submit a pull request. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
<!--value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database-->
* Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
* {@link #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)}. Will get {@link #customConversions()} applied.
@@ -70,20 +84,31 @@ public abstract class AbstractReactiveMongoConfiguration extends MongoConfigurat
/**
* Creates a {@link MappingMongoConverter} using the configured {@link #reactiveMongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
* {@link #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)}. Will get {@link #customConversions()} applied.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.