To create output fields in buckets, bucket operations can use `AggregationExpression` through `andOutput()` and xref:reference/aggregation-framework.adoc#mongo.aggregation.projection.expressions[SpEL expressions] through `andOutputExpression()`.
To create output fields in buckets, bucket operations can use `AggregationExpression` through `andOutput()` and xref:mongodb/aggregation-framework.adoc#mongo.aggregation.projection.expressions[SpEL expressions] through `andOutputExpression()`.
Note that further details regarding bucket expressions can be found in the https://docs.mongodb.org/manual/reference/operator/aggregation/bucket/[`$bucket` section] and
https://docs.mongodb.org/manual/reference/operator/aggregation/bucketAuto/[`$bucketAuto` section] of the MongoDB Aggregation Framework reference documentation.
@ -296,7 +296,7 @@ Note that further details regarding facet operation can be found in the https://
@@ -296,7 +296,7 @@ Note that further details regarding facet operation can be found in the https://
[[mongo.aggregation.sort-by-count]]
=== Sort By Count
Sort by count operations group incoming documents based on the value of a specified expression, compute the count of documents in each distinct group, and sort the results by count. It offers a handy shortcut to apply sorting when using xref:reference/aggregation-framework.adoc#mongo.aggregation.facet[Faceted Classification]. Sort by count operations require a grouping field or grouping expression. The following listing shows a sort by count example:
Sort by count operations group incoming documents based on the value of a specified expression, compute the count of documents in each distinct group, and sort the results by count. It offers a handy shortcut to apply sorting when using xref:mongodb/aggregation-framework.adoc#mongo.aggregation.facet[Faceted Classification]. Sort by count operations require a grouping field or grouping expression. The following listing shows a sort by count example:
.Sort by count example
====
@ -341,7 +341,7 @@ The preceding expression is translated into the following projection expression
@@ -341,7 +341,7 @@ The preceding expression is translated into the following projection expression
}]}
----
You can see examples in more context in xref:reference/aggregation-framework.adoc#mongo.aggregation.examples.example5[Aggregation Framework Example 5] and xref:reference/aggregation-framework.adoc#mongo.aggregation.examples.example6[Aggregation Framework Example 6]. You can find more usage examples for supported SpEL expression constructs in `SpelExpressionTransformerUnitTests`. The following table shows the SpEL transformations supported by Spring Data MongoDB:
You can see examples in more context in xref:mongodb/aggregation-framework.adoc#mongo.aggregation.examples.example5[Aggregation Framework Example 5] and xref:mongodb/aggregation-framework.adoc#mongo.aggregation.examples.example6[Aggregation Framework Example 6]. You can find more usage examples for supported SpEL expression constructs in `SpelExpressionTransformerUnitTests`. The following table shows the SpEL transformations supported by Spring Data MongoDB:
@ -91,9 +91,9 @@ If you prefer having more control over the session itself, you can obtain the `C
@@ -91,9 +91,9 @@ If you prefer having more control over the session itself, you can obtain the `C
NOTE: Reactive use of `ClientSession` is limited to Template API usage. There's currently no session integration with reactive repositories.
[[mongo.transactions]]
= MongoDB Transactions
== MongoDB Transactions
As of version 4, MongoDB supports https://www.mongodb.com/transactions[Transactions]. Transactions are built on top of xref:reference/client-session-transactions.adoc[Sessions] and, consequently, require an active `ClientSession`.
As of version 4, MongoDB supports https://www.mongodb.com/transactions[Transactions]. Transactions are built on top of xref:mongodb/client-session-transactions.adoc[Sessions] and, consequently, require an active `ClientSession`.
NOTE: Unless you specify a `MongoTransactionManager` within your application context, transaction support is *DISABLED*. You can use `setSessionSynchronization(ALWAYS)` to participate in ongoing non-native MongoDB transactions.
This approach lets you use the standard `MongoClient` instance, with the container using Spring's `MongoClientFactoryBean`/`ReactiveMongoClientFactoryBean`.
As compared to instantiating a `MongoClient` instance directly, the `FactoryBean` has the added advantage of also providing the container with an `ExceptionTranslator` implementation that translates MongoDB exceptions to exceptions in Spring's portable `DataAccessException` hierarchy for data access classes annotated with the `@Repository` annotation.
@ -170,7 +170,7 @@ public class MongoApplication {
@@ -170,7 +170,7 @@ public class MongoApplication {
}
}
----
The code in bold highlights the use of `SimpleMongoClientDbFactory` and is the only difference between the listing shown in the xref:reference/mongodb/getting-started.adoc[getting started section].
The code in bold highlights the use of `SimpleMongoClientDbFactory` and is the only difference between the listing shown in the xref:mongodb/getting-started.adoc[getting started section].
NOTE: Use `SimpleMongoClientDbFactory` when choosing `com.mongodb.client.MongoClient` as the entrypoint of choice.
@ -12,7 +12,7 @@ The GitHub https://github.com/spring-projects/spring-data-examples[spring-data-e
@@ -12,7 +12,7 @@ The GitHub https://github.com/spring-projects/spring-data-examples[spring-data-e
== Hello World
First, you need to set up a running MongoDB server. Refer to the https://docs.mongodb.org/manual/core/introduction/[MongoDB Quick Start guide] for an explanation on how to startup a MongoDB instance.
Once installed, starting MongoDB is typically a matter of running the following command: `${MONGO_HOME}/bin/mongod`
Once installed, starting MongoDB is typically a matter of running the following command: `/bin/mongod`
Then you can create a `Person` class to persist:
@ -54,8 +54,8 @@ Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
@@ -54,8 +54,8 @@ Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
Even in this simple example, there are few things to notice:
* You can instantiate the central helper class of Spring Mongo, xref:mongodb/mongo-template.adoc[`MongoTemplate`], by using the standard or reactive `MongoClient` object and the name of the database to use.
* The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See xref:mongodb/mapping.adoc[here].).
* You can instantiate the central helper class of Spring Mongo, xref:mongodb/template-api.adoc[`MongoTemplate`], by using the standard or reactive `MongoClient` object and the name of the database to use.
* The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See xref:mongodb/mapping/mapping.adoc[here].).
* Conventions are used for handling the `id` field, converting it to be an `ObjectId` when stored in the database.
* Mapping conventions can use field access. Notice that the `Person` class has only getters.
* If the constructor argument names match the field names of the stored document, they are used to instantiate the object
To retrieve a list of `SWCharacter` objects in Java, you would normally write the following:
[source,java]
@ -23,7 +19,6 @@ As in Java, `characters` in Kotlin is strongly typed, but Kotlin's clever type i
@@ -23,7 +19,6 @@ As in Java, `characters` in Kotlin is strongly typed, but Kotlin's clever type i
Spring Data MongoDB provides the following extensions:
* Reified generics support for `MongoOperations`, `ReactiveMongoOperations`, `FluentMongoOperations`, `ReactiveFluentMongoOperations`, and `Criteria`.
* xref:reference/mongodb/mongo-query/kotlin-support.adoc[Type-safe Queries for Kotlin]
* xref:mongodb/mongo-query/kotlin-support.adoc[Type-safe Queries for Kotlin]
* <<kotlin.coroutines>> extensions for `ReactiveFluentMongoOperations`.
@ -28,7 +28,7 @@ public class Payment {
@@ -28,7 +28,7 @@ public class Payment {
"date" : ISODate("2019-04-03T12:11:01.870Z") <3>
}
----
<1> String _id_ values that represent a valid `ObjectId` are converted automatically. See xref:reference/mongodb/mongo-template-save-update-remove.adoc#mongo-template.id-handling[How the `_id` Field is Handled in the Mapping Layer]
<1> String _id_ values that represent a valid `ObjectId` are converted automatically. See xref:mongodb/template-id-handling.adoc#mongo-template.id-handling[How the `_id` Field is Handled in the Mapping Layer]
for details.
<2> The desired target type is explicitly defined as `Decimal128` which translates to `NumberDecimal`. Otherwise the
`BigDecimal` value would have been truned into a `String`.
@ -101,5 +101,3 @@ class MyMongoConfiguration extends AbstractMongoClientConfiguration {
@@ -101,5 +101,3 @@ class MyMongoConfiguration extends AbstractMongoClientConfiguration {
@ -53,10 +53,10 @@ CAUTION: Lazy loading may require class proxies, that in turn, might need access
@@ -53,10 +53,10 @@ CAUTION: Lazy loading may require class proxies, that in turn, might need access
For those cases please consider falling back to an interface type (eg. switch from `ArrayList` to `List`) or provide the required `--add-opens` argument.
[[mapping-usage.document-references]]
= Using Document References
== Using Document References
Using `@DocumentReference` offers a flexible way of referencing entities in MongoDB.
While the goal is the same as when using xref:reference/document-references.adoc[DBRefs], the store representation is different.
While the goal is the same as when using xref:mongodb/mapping/document-references.adoc[DBRefs], the store representation is different.
`DBRef` resolves to a document with a fixed structure as outlined in the https://docs.mongodb.com/manual/reference/database-references/[MongoDB Reference documentation]. +
Document references, do not follow a specific format.
They can be literally anything, a single value, an entire document, basically everything that can be stored in MongoDB.
@ -51,6 +51,4 @@ NOTE: Lifecycle events are only emitted for root level types. Complex types used
@@ -51,6 +51,4 @@ NOTE: Lifecycle events are only emitted for root level types. Complex types used
WARNING: Lifecycle events depend on an `ApplicationEventMulticaster`, which in case of the `SimpleApplicationEventMulticaster` can be configured with a `TaskExecutor`, and therefore gives no guarantees when an Event is processed.
@ -9,8 +9,6 @@ The `MappingMongoConverter` also lets you map objects to documents without provi
@@ -9,8 +9,6 @@ The `MappingMongoConverter` also lets you map objects to documents without provi
This section describes the features of the `MappingMongoConverter`, including fundamentals, how to use conventions for mapping objects to documents and how to override those conventions with annotation-based mapping metadata.
@ -69,7 +67,7 @@ When querying and updating `MongoTemplate` will use the converter to handle conv
@@ -69,7 +67,7 @@ When querying and updating `MongoTemplate` will use the converter to handle conv
== Data Mapping and Type Conversion
This section explains how types are mapped to and from a MongoDB representation. Spring Data MongoDB supports all types that can be represented as BSON, MongoDB's internal document format.
In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion. See xref:reference/mongo-custom-conversions.adoc[Custom Conversions - Overriding Default Mapping] for further details.
In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion. See xref:mongodb/mapping/custom-conversions.adoc[Custom Conversions - Overriding Default Mapping] for further details.
The following provides samples of each available type conversion:
@ -193,12 +191,12 @@ calling `get()` before the actual conversion
@@ -193,12 +191,12 @@ calling `get()` before the actual conversion
| `LocalDate` +
(Joda, Java 8, JSR310-BackPort)
| converter / native (Java8)footnote:[Uses UTC zone offset. Configure via xref:reference/mapping.adoc#mapping-configuration[MongoConverterConfigurationAdapter]]
| converter / native (Java8)footnote:[Uses UTC zone offset. Configure via xref:mongodb/mapping/mapping.adoc#mapping-configuration[MongoConverterConfigurationAdapter]]
| converter / native (Java8)footnote:[Uses UTC zone offset. Configure via xref:reference/mapping.adoc#mapping-configuration[MongoConverterConfigurationAdapter]]
| converter / native (Java8)footnote:[Uses UTC zone offset. Configure via xref:mongodb/mapping/mapping.adoc#mapping-configuration[MongoConverterConfigurationAdapter]]
@ -403,7 +401,7 @@ public class Person {
@@ -403,7 +401,7 @@ public class Person {
IMPORTANT: The `@Id` annotation tells the mapper which property you want to use for the MongoDB `_id` property, and the `@Indexed` annotation tells the mapping framework to call `createIndex(…)` on that property of your document, making searches faster.
Automatic index creation is only done for types annotated with `@Document`.
WARNING: Auto index creation is **disabled** by default and needs to be enabled through the configuration (see xref:reference/mapping.adoc#mapping.index-creation[Index Creation]).
WARNING: Auto index creation is **disabled** by default and needs to be enabled through the configuration (see xref:mongodb/mapping/mapping.adoc#mapping.index-creation[Index Creation]).
[[mapping.index-creation]]
=== Index Creation
@ -904,7 +902,7 @@ class Nested {
@@ -904,7 +902,7 @@ class Nested {
[[mapping-usage-events]]
=== Mapping Framework Events
Events are fired throughout the lifecycle of the mapping process. This is described in the xref:reference/mongodb/mapping-usage-events.adoc[Lifecycle Events] section.
Events are fired throughout the lifecycle of the mapping process. This is described in the xref:mongodb/mapping/lifecycle-events.adoc[Lifecycle Events] section.
Declaring these beans in your Spring ApplicationContext causes them to be invoked whenever the event is dispatched.
While xref:reference/mongo-custom-conversions.adoc[type-based conversion] already offers ways to influence the conversion and representation of certain types within the target store, it has limitations when only certain values or properties of a particular type should be considered for conversion.
While xref:mongodb/mapping/custom-conversions.adoc[type-based conversion] already offers ways to influence the conversion and representation of certain types within the target store, it has limitations when only certain values or properties of a particular type should be considered for conversion.
Property-based converters allow configuring conversion rules on a per-property basis, either declaratively (via `@ValueConverter`) or programmatically (by registering a `PropertyValueConverter` for a specific property).
A `PropertyValueConverter` can transform a given value into its store representation (write) and back (read) as the following listing shows.
@ -15,9 +15,9 @@ Specific data types require deterministic encryption to preserve equality compar
@@ -15,9 +15,9 @@ Specific data types require deterministic encryption to preserve equality compar
== Automatic Encryption
MongoDB supports https://www.mongodb.com/docs/manual/core/csfle/[Client-Side Field Level Encryption] out of the box using the MongoDB driver with its Automatic Encryption feature.
Automatic Encryption requires a xref:reference/mongo-json-schema.adoc[JSON Schema] that allows to perform encrypted read and write operations without the need to provide an explicit en-/decryption step.
Automatic Encryption requires a xref:mongodb/template-collection-schema.adoc[JSON Schema] that allows to perform encrypted read and write operations without the need to provide an explicit en-/decryption step.
Please refer to the xref:reference/mongo-json-schema.adoc#mongo.jsonSchema.encrypted-fields[JSON Schema] section for more information on defining a JSON Schema that holds encryption information.
Please refer to the xref:mongodb/template-collection-schema.adoc#mongo.jsonSchema.encrypted-fields[JSON Schema] section for more information on defining a JSON Schema that holds encryption information.
To make use of a the `MongoJsonSchema` it needs to be combined with `AutoEncryptionSettings` which can be done eg. via a `MongoClientSettingsBuilderCustomizer`.
Explicit encryption uses the MongoDB driver's encryption library (`org.mongodb:mongodb-crypt`) to perform encryption and decryption tasks.
The `@ExplicitEncrypted` annotation is a combination of the `@Encrypted` annotation used for xref:reference/mongo-json-schema.adoc#mongo.jsonSchema.encrypted-fields[JSON Schema creation] and a xref:reference/mongo-property-converters.adoc[Property Converter].
The `@ExplicitEncrypted` annotation is a combination of the `@Encrypted` annotation used for xref:mongodb/template-collection-schema.adoc#mongo.jsonSchema.encrypted-fields[JSON Schema creation] and a xref:mongodb/mapping/property-converters.adoc[Property Converter].
In other words, `@ExplicitEncrypted` uses existing building blocks to combine them for simplified explicit encryption support.
[NOTE]
@ -112,7 +112,7 @@ Fields cannot be used in queries/aggregations.
@@ -112,7 +112,7 @@ Fields cannot be used in queries/aggregations.
By default, the `@ExplicitEncrypted(value=…)` attribute references a `MongoEncryptionConverter`.
It is possible to change the default implementation and exchange it with any `PropertyValueConverter` implementation by providing the according type reference.
To learn more about custom `PropertyValueConverters` and the required configuration, please refer to the xref:reference/mongo-property-converters.adoc[Property Converters - Mapping specific fields] section.
To learn more about custom `PropertyValueConverters` and the required configuration, please refer to the xref:mongodb/mapping/property-converters.adoc[Property Converters - Mapping specific fields] section.
The repository layer offers means to interact with xref:reference/aggregation-framework.adoc[the aggregation framework] via annotated repository query methods.
Similar to the xref:reference/mongo-repositories.adoc#mongodb.repositories.queries.json-based[JSON based queries], you can define a pipeline using the `org.springframework.data.mongodb.repository.Aggregation` annotation.
The repository layer offers means to interact with xref:mongodb/aggregation-framework.adoc[the aggregation framework] via annotated repository query methods.
Similar to the xref:mongodb/repositories/repositories.adoc#mongodb.repositories.queries.json-based[JSON based queries], you can define a pipeline using the `org.springframework.data.mongodb.repository.Aggregation` annotation.
The definition may contain simple placeholders like `?0` as well as link:{springDocsUrl}/core.html#expressions[SpEL expressions] `?#{ … }`.
@ -40,10 +40,10 @@ Be sure to add any other relevant settings needed to configure the tracer you ar
@@ -40,10 +40,10 @@ Be sure to add any other relevant settings needed to configure the tracer you ar
This should do it! You are now running with Spring Data MongoDB's usage of Spring Observability's `Observation` API.
include::{root-target}_conventions.adoc[]
include::{root-target}_metrics.adoc[]
include::{root-target}_spans.adoc[]
// include::{root-target}_conventions.adoc[]
//
// include::{root-target}_metrics.adoc[]
//
// include::{root-target}_spans.adoc[]
See also https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/database/#mongodb[OpenTelemetry Semantic Conventions] for further reference.
@ -44,7 +44,7 @@ public class Person {
@@ -44,7 +44,7 @@ public class Person {
====
Note that the entity defined in the preceding example has a property named `id` of type `String`. The default serialization mechanism used in `MongoTemplate` (which backs the repository support) regards properties named `id` as the document ID. Currently, we support `String`, `ObjectId`, and `BigInteger` as id-types.
Please see xref:reference/mongodb/mongo-template-save-update-remove.adoc#mongo-template.id-handling[ID mapping] for more information about on how the `id` field is handled in the mapping layer.
Please see xref:mongodb/template-id-handling.adoc#mongo-template.id-handling[ID mapping] for more information about on how the `id` field is handled in the mapping layer.
The following example shows how to create an interface that defines queries against the `Person` object from the preceding example:
Spring Data's Reactive MongoDB support comes with a reduced feature set compared to the blocking xref:reference/mongo-repositories.adoc[MongoDB Repositories].
Spring Data's Reactive MongoDB support comes with a reduced feature set compared to the blocking xref:mongodb/repositories/repositories.adoc[MongoDB Repositories].
It supports the following features:
* Query Methods using xref:reference/mongo-repositories.adoc#mongodb.repositories.queries[String queries and Query Derivation]
As you saw earlier in "`xref:reference/reactive-mongo-repositories.adoc#mongodb.reactive.repositories.queries.geo-spatial[Geo-spatial Repository Queries]`", a few keywords trigger geo-spatial operations within a MongoDB query. The `Near` keyword allows some further modification, as the next few examples show.
The following example shows how to define a `near` query that finds all persons with a given distance of a given point:
@ -19,7 +19,7 @@ For most tasks, you should use `ReactiveMongoTemplate` or the repository support
@@ -19,7 +19,7 @@ For most tasks, you should use `ReactiveMongoTemplate` or the repository support
Spring MongoDB support requires MongoDB 2.6 or higher and Java SE 8 or higher.
First, you need to set up a running MongoDB server. Refer to the https://docs.mongodb.org/manual/core/introduction/[MongoDB Quick Start guide] for an explanation on how to startup a MongoDB instance. Once installed, starting MongoDB is typically a matter of running the following command: `${MONGO_HOME}/bin/mongod`
First, you need to set up a running MongoDB server. Refer to the https://docs.mongodb.org/manual/core/introduction/[MongoDB Quick Start guide] for an explanation on how to startup a MongoDB instance. Once installed, starting MongoDB is typically a matter of running the following command: `/bin/mongod`
To create a Spring project in STS, go to File -> New -> Spring Template Project -> Simple Spring Utility Project and press Yes when prompted. Then enter a project and a package name, such as org.spring.mongodb.example.
@ -40,7 +40,7 @@ Then add the following to the pom.xml dependencies section.
@@ -40,7 +40,7 @@ Then add the following to the pom.xml dependencies section.
@ -127,8 +127,8 @@ Running the preceding class produces the following output:
@@ -127,8 +127,8 @@ Running the preceding class produces the following output:
Even in this simple example, there are a few things to take notice of:
* You can instantiate the central helper class of Spring Mongo (xref:reference/reactive-mongodb.adoc#mongo.reactive.template[`ReactiveMongoTemplate`]) by using the standard `com.mongodb.reactivestreams.client.MongoClient` object and the name of the database to use.
* The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See xref:reference/mapping.adoc[here].).
* You can instantiate the central helper class of Spring Mongo by using the standard `com.mongodb.reactivestreams.client.MongoClient` object and the name of the database to use.
* The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See xref:mongodb/mapping/mapping.adoc[here].).
* Conventions are used for handling the ID field, converting it to be an `ObjectId` when stored in the database.
* Mapping conventions can use field access. Notice that the `Person` class has only getters.
* If the constructor argument names match the field names of the stored document, they are used to instantiate the object
@ -250,7 +250,7 @@ public class MongoApp {
@@ -250,7 +250,7 @@ public class MongoApp {
}
----
The use of `SimpleReactiveMongoDatabaseFactory` is the only difference between the listing shown in the xref:reference/reactive-mongodb.adoc#mongodb-reactive-getting-started[getting started section].
The use of `SimpleReactiveMongoDatabaseFactory` is the only difference between the listing shown in the xref:mongodb/getting-started.adoc[getting started section].
[[mongo.reactive.mongo-db-factory-java]]
=== Registering a ReactiveMongoDatabaseFactory Instance by Using Java-based Metadata
@ -292,18 +292,17 @@ The `ReactiveMongoTemplate` class, located in the `org.springframework.data.mong
@@ -292,18 +292,17 @@ The `ReactiveMongoTemplate` class, located in the `org.springframework.data.mong
NOTE: Once configured, `ReactiveMongoTemplate` is thread-safe and can be reused across multiple instances.
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the `MongoConverter` interface. Spring provides a default implementation with `MongoMappingConverter`, but you can also write your own converter. See the xref:reference/mongo-custom-conversions.adoc[section on `MongoConverter` instances] for more detailed information.
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the `MongoConverter` interface. Spring provides a default implementation with `MongoMappingConverter`, but you can also write your own converter. See the xref:mongodb/mapping/custom-conversions.adoc[section on `MongoConverter` instances] for more detailed information.
The `ReactiveMongoTemplate` class implements the `ReactiveMongoOperations` interface. As much as possible, the methods on `ReactiveMongoOperations` mirror methods available on the MongoDB driver `Collection` object, to make the API familiar to existing MongoDB developers who are used to the driver API. For example, you can find methods such as `find`, `findAndModify`, `findOne`, `insert`, `remove`, `save`, `update`, and `updateMulti`. The design goal is to make it as easy as possible to transition between the use of the base MongoDB driver and `ReactiveMongoOperations`. A major difference between the two APIs is that `ReactiveMongoOperations` can be passed domain objects instead of `Document`, and there are fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `Document` to specify the parameters for those operations.
NOTE: The preferred way to reference the operations on `ReactiveMongoTemplate` instance is through its `ReactiveMongoOperations` interface.
The default converter implementation used by `ReactiveMongoTemplate` is `MappingMongoConverter`. While the `MappingMongoConverter` can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names. These conventions as well as the use of mapping annotations are explained in the xref:reference/mapping.adoc[Mapping chapter].
The default converter implementation used by `ReactiveMongoTemplate` is `MappingMongoConverter`. While the `MappingMongoConverter` can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names. These conventions as well as the use of mapping annotations are explained in the xref:mongodb/mapping/mapping.adoc[Mapping chapter].
Another central feature of `ReactiveMongoTemplate` is exception translation of exceptions thrown in the MongoDB Java driver into Spring's portable Data Access Exception hierarchy. See the section on xref:reference/mongodb/mongo-exception.adoc[exception translation] for more information.
There are many convenience methods on `ReactiveMongoTemplate` to help you easily perform common tasks. However, if you need to access the MongoDB driver API directly to access functionality not explicitly exposed by the MongoTemplate, you can use one of several `execute` callback methods to access underlying driver APIs. The `execute` callbacks give you a reference to either a `com.mongodb.reactivestreams.client.MongoCollection` or a `com.mongodb.reactivestreams.client.MongoDatabase` object. See xref:reference/reactive-mongodb.adoc#mongo.reactive.executioncallback[Execution Callbacks] for more information.
Another central feature of `ReactiveMongoTemplate` is exception translation of exceptions thrown in the MongoDB Java driver into Spring's portable Data Access Exception hierarchy.
There are many convenience methods on `ReactiveMongoTemplate` to help you easily perform common tasks. However, if you need to access the MongoDB driver API directly to access functionality not explicitly exposed by the MongoTemplate, you can use one of several `execute` callback methods to access underlying driver APIs. The `execute` callbacks give you a reference to either a `com.mongodb.reactivestreams.client.MongoCollection` or a `com.mongodb.reactivestreams.client.MongoDatabase` object.
[[mongo.reactive.template.instantiating]]
=== Instantiating ReactiveMongoTemplate
@ -457,8 +456,6 @@ The preceding example includes implicit conversion between a `String` and `Objec
@@ -457,8 +456,6 @@ The preceding example includes implicit conversion between a `String` and `Objec
NOTE: The preceding example is meant to show the use of save, update, and remove operations on `ReactiveMongoTemplate` and not to show complex mapping or chaining functionality.
"`xref:reference/mongodb/mongo-query.adoc[Querying Documents]`" explains the query syntax used in the preceding example in more detail. Additional documentation can be found in xref:reference/mongodb/mongo-template.adoc[the blocking `MongoTemplate`] section.
@ -31,7 +31,7 @@ public class Person {
@@ -31,7 +31,7 @@ public class Person {
Note that the domain type shown in the preceding example has a property named `id` of type `String`.The default serialization mechanism used in `MongoTemplate` (which backs the repository support) regards properties named `id` as the document ID.
Currently, we support `String`, `ObjectId`, and `BigInteger` as ID types.
Please see xref:reference/mongodb/mongo-template-save-update-remove.adoc#mongo-template.id-handling[ID mapping] for more information about on how the `id` field is handled in the mapping layer.
Please see xref:mongodb/template-id-handling.adoc#mongo-template.id-handling[ID mapping] for more information about on how the `id` field is handled in the mapping layer.
Now that we have a domain object, we can define an interface that uses it, as follows:
The update is "`as is`" and does not bind any parameters.
<2> The actual increment value is defined by the `increment` method argument that is bound to the `?1` placeholder.
<3> Use the Spring Expression Language (SpEL) for parameter binding.
<4> Use the `pipeline` attribute to issue xref:reference/mongodb/mongo-template-save-update-remove.adoc#mongo-template.aggregation-update[aggregation pipeline updates].
<4> Use the `pipeline` attribute to issue xref:mongodb/template-crud-operations.adoc#mongo-template.aggregation-update[aggregation pipeline updates].
<5> The update may contain complex objects.
<6> Combine a xref:reference/mongo-repositories.adoc#mongodb.repositories.queries.json-based[string based query] with an update.
<6> Combine a xref:mongodb/repositories/repositories.adoc#mongodb.repositories.queries.json-based[string based query] with an update.
====
WARNING: Repository updates do not emit persistence nor mapping lifecycle events.
MongoDB's full-text search feature is store-specific and, therefore, can be found on `MongoRepository` rather than on the more general `CrudRepository`.
We need a document with a full-text index (see "`xref:reference/mapping.adoc#mapping-usage-indexes.text-index[Text Indexes]`" to learn how to create a full-text index).
We need a document with a full-text index (see "`xref:mongodb/mapping/mapping.adoc#mapping-usage-indexes.text-index[Text Indexes]`" to learn how to create a full-text index).
Additional methods on `MongoRepository` take `TextCriteria` as an input parameter.
In addition to those explicit methods, it is also possible to add a `TextCriteria`-derived repository method.
@ -87,7 +87,7 @@ NOTE: Using projections allows `MongoTemplate` to optimize result mapping by lim
@@ -87,7 +87,7 @@ NOTE: Using projections allows `MongoTemplate` to optimize result mapping by lim
by the projection target type. This applies as long as the `Query` itself does not contain any field restriction and the
target type is a closed interface or DTO projection.
WARNING: Projections must not be applied to xref:mongodb/document-references.adoc[DBRefs].
WARNING: Projections must not be applied to xref:mongodb/mapping/document-references.adoc[DBRefs].
You can switch between retrieving a single entity and retrieving multiple entities as a `List` or a `Stream` through the terminating methods: `first()`, `one()`, `all()`, or `stream()`.
@ -122,4 +122,4 @@ Look into the implementation for more details on the mapping.
@@ -122,4 +122,4 @@ Look into the implementation for more details on the mapping.
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the `MongoConverter` interface.
Spring provides `MappingMongoConverter`, but you can also write your own converter.
While the `MappingMongoConverter` can use additional metadata to specify the mapping of objects to documents, it can also convert objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names.
These conventions, as well as the use of mapping annotations, are explained in the "`xref:mongodb/mapping.adoc[Mapping]`" chapter.
These conventions, as well as the use of mapping annotations, are explained in the "`xref:mongodb/mapping/mapping.adoc[Mapping]`" chapter.
@ -40,7 +40,7 @@ You can create standard, geospatial, and text indexes by using the `IndexDefinit
@@ -40,7 +40,7 @@ You can create standard, geospatial, and text indexes by using the `IndexDefinit
<1> Obtain a schema builder to configure the schema with a fluent API.
<2> Configure required properties either directly as shown here or with more details as in 3.
<3> Configure the required String-typed `firstname` field, allowing only `luke` and `han` values. Properties can be typed or untyped. Use a static import of `JsonSchemaProperty` to make the syntax slightly more compact and to get entry points such as `string(…)`.
<4> Build the schema object. Use the schema to create either a collection or xref:reference/mongodb/mongo-query/template.adoc#mongodb-template-query.criteria[query documents].
<4> Build the schema object.
====
There are already some predefined and strongly typed schema objects (`JsonSchemaObject` and `JsonSchemaProperty`) available
@ -94,7 +94,7 @@ It's important, schema changes can be hard.
@@ -94,7 +94,7 @@ It's important, schema changes can be hard.
However, there might be times when one does not want to balked with it, and that is where `JsonSchemaCreator` comes into play.
`JsonSchemaCreator` and its default implementation generates a `MongoJsonSchema` out of domain types metadata provided by the mapping infrastructure.
This means, that xref:reference/mapping.adoc#mapping-usage-annotations[annotated properties] as well as potential xref:reference/mapping.adoc#mapping-configuration[custom conversions] are considered.
This means, that xref:mongodb/mapping/mapping.adoc#mapping-usage-annotations[annotated properties] as well as potential xref:mongodb/mapping/mapping.adoc#mapping-configuration[custom conversions] are considered.
Nest to lifecycle events the template invokes xref:mongodb/mongo-entity-callbacks.adoc[EntityCallbacks] which can be (if not auto configured) set via the template API.
Nest to lifecycle events the template invokes xref:mongodb/mapping/entity-callbacks.adoc[EntityCallbacks] which can be (if not auto configured) set via the template API.
By setting `MongoTemplate#useEstimatedCount(...)` to `true` _MongoTemplate#count(...)_ operations, that use an empty filter query, will be delegated to `estimatedCount`, as long as there is no transaction active and the template is not bound to a xref:mongodb/client-session-transactions.adoc[session].
Please refer to to the xref:mongodb/mongo-query-count.adoc#mongo.query.count[Counting Documents] section for more information.
Please refer to to the xref:mongodb/template-document-count.adoc#mongo.query.count[Counting Documents] section for more information.
@ -108,7 +108,7 @@ public class ReactiveMongoApplication {
@@ -108,7 +108,7 @@ public class ReactiveMongoApplication {
`MongoConverter` caused implicit conversion between a `String` and an `ObjectId` stored in the database by recognizing (through convention) the `Id` property name.
The preceding example is meant to show the use of save, update, and remove operations on `MongoTemplate` / `ReactiveMongoTemplate` and not to show complex mapping functionality.
The query syntax used in the preceding example is explained in more detail in the section "`xref:mongodb/mongo-query.adoc[Querying Documents]`".
The query syntax used in the preceding example is explained in more detail in the section "`xref:mongodb/template-query-operations.adoc[Querying Documents]`".
IMPORTANT: MongoDB requires that you have an `_id` field for all documents. Please refer to the xref:mongodb/template-id-handling.adoc[id handling] section for details on the special treatment of this field.
@ -22,7 +22,7 @@ If the application is fine with the limitations of working upon collection stati
@@ -22,7 +22,7 @@ If the application is fine with the limitations of working upon collection stati
[TIP]
====
By setting `MongoTemplate#useEstimatedCount(...)` to `true` _MongoTemplate#count(...)_ operations, that use an empty filter query, will be delegated to `estimatedCount`, as long as there is no transaction active and the template is not bound to a xref:reference/client-session-transactions.adoc[session].
By setting `MongoTemplate#useEstimatedCount(...)` to `true` _MongoTemplate#count(...)_ operations, that use an empty filter query, will be delegated to `estimatedCount`, as long as there is no transaction active and the template is not bound to a xref:mongodb/client-session-transactions.adoc[session].
It will still be possible to obtain exact numbers via `MongoTemplate#exactCount`, but may speed up things.
@ -96,7 +96,7 @@ The `Criteria` class provides the following methods, all of which correspond to
@@ -96,7 +96,7 @@ The `Criteria` class provides the following methods, all of which correspond to
* `Criteria` *sampleRate* `(double sampleRate)` Creates a criterion using the `$sampleRate` operator
* `Criteria` *size* `(int s)` Creates a criterion using the `$size` operator
* `Criteria` *type* `(int t)` Creates a criterion using the `$type` operator
* `Criteria` *matchingDocumentStructure* `(MongoJsonSchema schema)` Creates a criterion using the `$jsonSchema` operator for xref:mongodb/mongo-json-schema.adoc[JSON schema criteria]. `$jsonSchema` can only be applied on the top level of a query and not property specific. Use the `properties` attribute of the schema to match against nested fields.
* `Criteria` *matchingDocumentStructure* `(MongoJsonSchema schema)` Creates a criterion using the `$jsonSchema` operator for xref:mongodb/template-collection-schema.adoc[JSON schema criteria]. `$jsonSchema` can only be applied on the top level of a query and not property specific. Use the `properties` attribute of the schema to match against nested fields.
* `Criteria` *bits()* is the gateway to https://docs.mongodb.com/manual/reference/operator/query-bitwise/[MongoDB bitwise query operators] like `$bitsAllClear`.
<4> Use SpEL along with an `AggregationExpression` to invoke expression functions. Field names are mapped to the ones used in the domain model.
====
`@Query(fields="…")` allows usage of expression field projections at `Repository` level as described in xref:mongodb/mongo-repositories.adoc#mongodb.repositories.queries.json-based[MongoDB JSON-based Query Methods and Field Restriction].
`@Query(fields="…")` allows usage of expression field projections at `Repository` level as described in xref:mongodb/repositories/repositories.adoc#mongodb.repositories.queries.json-based[MongoDB JSON-based Query Methods and Field Restriction].
MongoDB supports GeoSpatial queries through the use of operators such as `$near`, `$within`, `geoWithin`, and `$nearSphere`. Methods specific to geospatial queries are available on the `Criteria` class. There are also a few shape classes (`Box`, `Circle`, and `Point`) that are used in conjunction with geospatial related `Criteria` methods.
@ -653,7 +653,7 @@ Returning the 3 Documents just like the GeoJSON variant:
@@ -653,7 +653,7 @@ Returning the 3 Documents just like the GeoJSON variant:
Since version 2.6 of MongoDB, you can run full-text queries by using the `$text` operator. Methods and operations specific to full-text queries are available in `TextQuery` and `TextCriteria`. When doing full text search, see the https://docs.mongodb.org/manual/reference/operator/query/text/#behavior[MongoDB reference] for its behavior and limitations.
Before you can actually use full-text search, you must set up the search index correctly.
See xref:mongodb/mapping.adoc#mapping-usage-indexes.text-index[Text Index] for more detail on how to create index structures.
See xref:mongodb/mapping/mapping.adoc#mapping-usage-indexes.text-index[Text Index] for more detail on how to create index structures.
The following example shows how to set up a full-text search:
[source,javascript]
@ -775,7 +775,7 @@ Doing so forces exact document matching for all property values and the property
@@ -775,7 +775,7 @@ Doing so forces exact document matching for all property values and the property
[NOTE]
====
`UntypedExampleMatcher` is likely the right choice for you if you are storing different entities within a single collection or opted out of writing xref:mongodb/mongodb/mongo-template-save-update-remove.adoc#mongo-template.type-mapping[type hints].
`UntypedExampleMatcher` is likely the right choice for you if you are storing different entities within a single collection or opted out of writing type hints.
Also, keep in mind that using `@TypeAlias` requires eager initialization of the `MappingContext`. To do so, configure `initialEntitySet` to to ensure proper alias resolution for read operations.
Using collations with collection operations is a matter of specifying a `Collation` instance in your query or operation options, as the following two examples show:
This chapter explains the basic foundations of Spring Data repositories and Cassandra specifics.
Before continuing to the Cassandra specifics, make sure you have a sound understanding of the basic concepts.
This chapter explains the basic foundations of Spring Data repositories and MongoDB specifics.
Before continuing to the MongoDB specifics, make sure you have a sound understanding of the basic concepts.
The goal of the Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
NOTE: Cassandra provides no means to generate identifiers upon inserting data.
[NOTE]
====
Cassandra provides no means to generate identifiers upon inserting data.
As consequence, entities must be associated with identifier values.
Spring Data defaults to identifier inspection to determine whether an entity is new.
If you want to use xref:cassandra/auditing.adoc[auditing] make sure to either use xref:cassandra/template.adoc#cassandra.template.optimistic-locking[Optimistic Locking] or implement `Persistable` for proper entity state detection.
If you want to use xref:mongodb/auditing.adoc[auditing] make sure to either use xref:mongodb/template-crud-operations.adoc#mongo-template.optimistic-locking[Optimistic Locking] or implement `Persistable` for proper entity state detection.