DATAMONGO-2509 - Polishing.
Fix typos, improve wording. Reworks documentation specific to MongoDB 3 and 4. Original pull request: #853.
This commit is contained in:
@@ -1,19 +1,3 @@
|
||||
/*
|
||||
* Copyright 2020 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* MongoDB driver-specific utility classes for Json conversion.
|
||||
*/
|
||||
|
||||
@@ -33,7 +33,6 @@ include::reference/mapping.adoc[leveloffset=+1]
|
||||
include::reference/sharding.adoc[leveloffset=+1]
|
||||
include::reference/kotlin.adoc[leveloffset=+1]
|
||||
include::reference/jmx.adoc[leveloffset=+1]
|
||||
include::reference/mongo-3.adoc[leveloffset=+1]
|
||||
|
||||
[[appendix]]
|
||||
= Appendix
|
||||
|
||||
@@ -385,16 +385,22 @@ 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 turned **OFF** by default and need to be enabled via the configuration (see <<mapping.index-creation>>).
|
||||
WARNING: Auto index creation is **disabled** by default and needs to be enabled through the configuration (see <<mapping.index-creation>>).
|
||||
|
||||
[[mapping.index-creation]]
|
||||
=== Index Creation
|
||||
|
||||
Spring Data MongoDB can automatically create indexes for entity types annotated with `@Document`. Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecyle and performance impact. Indexes are automatically created for the initial entity set on application startup and when accessing an entity type for the first time while the application runs.
|
||||
Spring Data MongoDB can automatically create indexes for entity types annotated with `@Document`.
|
||||
Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecyle and performance impact.
|
||||
Indexes are automatically created for the initial entity set on application startup and when accessing an entity type for the first time while the application runs.
|
||||
|
||||
We generally recommend explicit index creation for application-based control of indexes as Spring Data cannot automatically create indexes for collections that were recreated while the application was running.
|
||||
|
||||
`IndexResolver` provides an abstraction for programmatic index definition creation if you want to make use of `@Indexed` annotations such as `@GeoSpatialIndexed`, `@TextIndexed`, `@CompoundIndex`. You can use index definitions with `IndexOperations` to create indexes. A good point in time for index creation is on application startup, specifically after the application context was refreshed, triggered by observing `ContextRefreshedEvent`. This event guarantees that the context is fully initialized. Note that at this time other components, especially bean factories might have access to the MongoDB database.
|
||||
`IndexResolver` provides an abstraction for programmatic index definition creation if you want to make use of `@Indexed` annotations such as `@GeoSpatialIndexed`, `@TextIndexed`, `@CompoundIndex`.
|
||||
You can use index definitions with `IndexOperations` to create indexes.
|
||||
A good point in time for index creation is on application startup, specifically after the application context was refreshed, triggered by observing `ContextRefreshedEvent`.
|
||||
This event guarantees that the context is fully initialized.
|
||||
Note that at this time other components, especially bean factories might have access to the MongoDB database.
|
||||
|
||||
.Programmatic Index Creation for a single Domain Type
|
||||
====
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
[[mongo.mongo-3]]
|
||||
= MongoDB 3.0 Support
|
||||
|
||||
Spring Data MongoDB requires MongoDB Java driver generations 4 when connecting to a MongoDB 2.6/3.0 server running MMap.v1 or a MongoDB server 3.0 using MMap.v1 or the WiredTiger storage engine.
|
||||
|
||||
NOTE: See the driver- and database-specific documentation for major differences between those engines.
|
||||
|
||||
== Using Spring Data MongoDB with MongoDB 3.0
|
||||
|
||||
The rest of this section describes how to use Spring Data MongoDB with MongoDB 3.0.
|
||||
|
||||
[[mongo.mongo-3.configuration]]
|
||||
=== Configuration Options
|
||||
|
||||
Some of the configuration options have been changed or removed for the `mongo-java-driver`. The following options are ignored when using the generation 3 driver:
|
||||
|
||||
* `autoConnectRetry`
|
||||
* `maxAutoConnectRetryTime`
|
||||
* `slaveOk`
|
||||
|
||||
Generally, you should use the `<mongo:mongo-client ... />` and `<mongo:client-options ... />` elements instead of `<mongo:mongo ... />` when doing XML based configuration, since those elements provide you with attributes that are only valid for the third generation Java driver. The follwoing example shows how to configure a Mongo client connection:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo https://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:mongo-client host="127.0.0.1" port="27017">
|
||||
<mongo:client-options write-concern="NORMAL" />
|
||||
</mongo:mongo-client>
|
||||
|
||||
</beans>
|
||||
----
|
||||
|
||||
[[mongo.mongo-3.write-concern]]
|
||||
=== `WriteConcern` and `WriteConcernChecking`
|
||||
|
||||
`WriteConcern.NONE`, which had been used as the default by Spring Data MongoDB, was removed in 3.0. Therefore, in a MongoDB 3 environment, the `WriteConcern` defaults to `WriteConcern.UNACKNOWLEGED`. If `WriteResultChecking.EXCEPTION` is enabled, the `WriteConcern` is altered to `WriteConcern.ACKNOWLEDGED` for write operations. Otherwise, errors during execution would not be thrown correctly, since they are not raised by the driver.
|
||||
|
||||
[[mongo.mongo-3.authentication]]
|
||||
=== Authentication
|
||||
|
||||
MongoDB Server generation 3 changed the authentication model when connecting to the DB. Therefore, some of the configuration options available for authentication are no longer valid. You should use the `MongoClient`-specific options when setting credentials with `MongoCredential` to provide authentication data, as the following example shows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
public class ApplicationContextEventTestsAppConfig extends AbstractMongoClientConfiguration {
|
||||
|
||||
@Override
|
||||
public String getDatabaseName() {
|
||||
return "database";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
public MongoClient mongoClient() {
|
||||
return new MongoClient(singletonList(new ServerAddress("127.0.0.1", 27017)),
|
||||
singletonList(MongoCredential.createCredential("name", "db", "pwd".toCharArray())));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
In order to use authentication with XML configuration, you can use the `credentials` attribute on `<mongo-client>`, as the following example shows:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo https://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:mongo-client credentials="user:password@database" />
|
||||
|
||||
</beans>
|
||||
----
|
||||
|
||||
[[mongo.mongo-3.validation]]
|
||||
=== Server-side Validation
|
||||
|
||||
MongoDB supports https://docs.mongodb.com/manual/core/schema-validation/[Schema Validation] as of version 3.2 with query operators
|
||||
and as of version 3.6 JSON-schema based validation.
|
||||
|
||||
This chapter will point out the specialties for validation in MongoDB and how to apply JSON schema validation.
|
||||
|
||||
[[mongo.mongo-3.validation.json-schema]]
|
||||
==== JSON Schema Validation
|
||||
|
||||
MongoDB 3.6 allows validation and querying of documents with JSON schema draft 4 (including core specification and validation specification) with some differences. `$jsonSchema` can be used in a document validator (when creating a collection), which enforces that inserted or updated documents are valid against the schema. It can also be used to query for documents with the `find` command or `$match` aggregation stage.
|
||||
|
||||
Spring Data MongoDB supports MongoDB's specific JSON schema implementation to define and use schemas. See <<mongo.jsonSchema,JSON Schema>> for further details.
|
||||
|
||||
[[mongo.mongo-3.validation.query-expression]]
|
||||
==== Query Expression Validation
|
||||
|
||||
In addition to the <<mongo.mongo-3.validation.json-schema>>, MongoDB supports (as of version 3.2) validating documents against a given structure described by a query. The structure can be built from `Criteria` objects in the same way as they are used for defining queries. The following example shows how to create and use such a validator:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
Criteria queryExpression = Criteria.where("lastname").ne(null).type(2)
|
||||
.and("age").ne(null).type(16).gt(0).lte(150);
|
||||
|
||||
Validator validator = Validator.criteria(queryExpression);
|
||||
|
||||
template.createCollection(Person.class, CollectionOptions.empty().validator(validator));
|
||||
----
|
||||
|
||||
NOTE: The field names used within the query expression are mapped to the domain types property names, taking potential `@Field` annotations into account.
|
||||
|
||||
[[mongo.mongo-3.misc]]
|
||||
=== Miscellaneous Details
|
||||
|
||||
This section covers briefly lists additional things to keep in mind when using the 4.0 driver:
|
||||
|
||||
* `IndexOperations.resetIndexCache()` is no longer supported.
|
||||
* Any `MapReduceOptions.extraOption` is silently ignored.
|
||||
* `WriteResult` no longer holds error information but, instead, throws an `Exception`.
|
||||
* `MongoOperations.executeInSession(…)` no longer calls `requestStart` and `requestDone`.
|
||||
* Index name generation has become a driver-internal operation.
|
||||
Spring Data MongoDB still uses the 2.x schema to generate names.
|
||||
* Some `Exception` messages differ between the generation 2 and 3 servers as well as between the MMap.v1 and WiredTiger storage engines.
|
||||
@@ -9,7 +9,7 @@ This chapter points out the specialties for repository support for MongoDB. This
|
||||
[[mongo-repo-usage]]
|
||||
== Usage
|
||||
|
||||
To access domain entities stored in a MongoDB, you can use our sophisticated repository support that eases implementation quite significantly. To do so, create an interface for your repository, as the following example shows:
|
||||
To access domain entities stored in a MongoDB, you can use our sophisticated repository support that eases implementation quite significantly.To do so, create an interface for your repository, as the following example shows:
|
||||
|
||||
.Sample Person entity
|
||||
====
|
||||
@@ -28,7 +28,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.
|
||||
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 <<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:
|
||||
@@ -49,7 +49,7 @@ public interface PersonRepository extends PagingAndSortingRepository<Person, Str
|
||||
Right now this interface serves only to provide type information, but we can add additional methods to it later.
|
||||
|
||||
To start using the repository, use the `@EnableMongoRepositories` annotation.
|
||||
That annotation carries the same attributes as the namespace element. If no base package is configured, the infrastructure scans the package of the annotated configuration class. The following example shows how to use Java configuration for a repository:
|
||||
That annotation carries the same attributes as the namespace element.If no base package is configured, the infrastructure scans the package of the annotated configuration class.The following example shows how to use Java configuration for a repository:
|
||||
|
||||
.Java configuration for repositories
|
||||
====
|
||||
@@ -100,11 +100,11 @@ If you would rather go with XML based configuration add the following content:
|
||||
----
|
||||
====
|
||||
|
||||
This namespace element causes the base packages to be scanned for interfaces that extend `MongoRepository` and create Spring beans for each one found. By default, the repositories get a `MongoTemplate` Spring bean wired that is called `mongoTemplate`, so you only need to configure `mongo-template-ref` explicitly if you deviate from this convention.
|
||||
This namespace element causes the base packages to be scanned for interfaces that extend `MongoRepository` and create Spring beans for each one found.By default, the repositories get a `MongoTemplate` Spring bean wired that is called `mongoTemplate`, so you only need to configure `mongo-template-ref` explicitly if you deviate from this convention.
|
||||
|
||||
|
||||
|
||||
Because our domain repository extends `PagingAndSortingRepository`, it provides you with CRUD operations as well as methods for paginated and sorted access to the entities. Working with the repository instance is just a matter of dependency injecting it into a client. Consequently, accessing the second page of `Person` objects at a page size of 10 would resemble the following code:
|
||||
Because our domain repository extends `PagingAndSortingRepository`, it provides you with CRUD operations as well as methods for paginated and sorted access to the entities.Working with the repository instance is just a matter of dependency injecting it into a client.Consequently, accessing the second page of `Person` objects at a page size of 10 would resemble the following code:
|
||||
|
||||
.Paging access to Person entities
|
||||
====
|
||||
@@ -120,13 +120,13 @@ public class PersonRepositoryTests {
|
||||
public void readsFirstPageCorrectly() {
|
||||
|
||||
Page<Person> persons = repository.findAll(PageRequest.of(0, 10));
|
||||
assertThat(persons.isFirstPage(), is(true));
|
||||
assertThat(persons.isFirstPage()).isTrue();
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The preceding example creates an application context with Spring's unit test support, which performs annotation-based dependency injection into test cases. Inside the test method, we use the repository to query the datastore. We hand the repository a `PageRequest` instance that requests the first page of `Person` objects at a page size of 10.
|
||||
The preceding example creates an application context with Spring's unit test support, which performs annotation-based dependency injection into test cases.Inside the test method, we use the repository to query the datastore.We hand the repository a `PageRequest` instance that requests the first page of `Person` objects at a page size of 10.
|
||||
|
||||
[[mongodb.repositories.queries]]
|
||||
== Query Methods
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
The MongoDB support contains a wide range of features:
|
||||
|
||||
* Spring configuration support with Java-based `@Configuration` classes or an XML namespace for a Mongo driver instance and replica sets.
|
||||
* `MongoTemplate` helper class that increases productivity when performing common Mongo operations. Includes integrated object mapping between documents and POJOs.
|
||||
* `MongoTemplate` helper class that increases productivity when performing common Mongo operations.Includes integrated object mapping between documents and POJOs.
|
||||
* Exception translation into Spring's portable Data Access Exception hierarchy.
|
||||
* Feature-rich Object Mapping integrated with Spring's Conversion Service.
|
||||
* Annotation-based mapping metadata that is extensible to support other metadata formats.
|
||||
@@ -669,9 +669,9 @@ public class StringToObjectId {
|
||||
[[mongo-template.type-mapping]]
|
||||
=== Type Mapping
|
||||
|
||||
MongoDB collections can contain documents that represent instances of a variety of types. This feature can be useful if you store a hierarchy of classes or have a class with a property of type `Object`. In the latter case, the values held inside that property have to be read in correctly when retrieving the object. Thus, we need a mechanism to store type information alongside the actual document.
|
||||
MongoDB collections can contain documents that represent instances of a variety of types.This feature can be useful if you store a hierarchy of classes or have a class with a property of type `Object`.In the latter case, the values held inside that property have to be read in correctly when retrieving the object.Thus, we need a mechanism to store type information alongside the actual document.
|
||||
|
||||
To achieve that, the `MappingMongoConverter` uses a `MongoTypeMapper` abstraction with `DefaultMongoTypeMapper` as its main implementation. Its default behavior to store the fully qualified classname under `_class` inside the document. Type hints are written for top-level documents as well as for every value (if it is a complex type and a subtype of the declared property type). The following example (with a JSON representation at the end) shows how the mapping works:
|
||||
To achieve that, the `MappingMongoConverter` uses a `MongoTypeMapper` abstraction with `DefaultMongoTypeMapper` as its main implementation.Its default behavior to store the fully qualified classname under `_class` inside the document.Type hints are written for top-level documents as well as for every value (if it is a complex type and a subtype of the declared property type).The following example (with a JSON representation at the end) shows how the mapping works:
|
||||
|
||||
.Type mapping
|
||||
====
|
||||
@@ -697,11 +697,11 @@ mongoTemplate.save(sample);
|
||||
----
|
||||
====
|
||||
|
||||
Spring Data MongoDB stores the type information as the last field for the actual root class as well as for the nested type (because it is complex and a subtype of `Contact`). So, if you now use `mongoTemplate.findAll(Object.class, "sample")`, you can find out that the document stored is a `Sample` instance. You can also find out that the value property is actually a `Person`.
|
||||
Spring Data MongoDB stores the type information as the last field for the actual root class as well as for the nested type (because it is complex and a subtype of `Contact`).So, if you now use `mongoTemplate.findAll(Object.class, "sample")`, you can find out that the document stored is a `Sample` instance.You can also find out that the value property is actually a `Person`.
|
||||
|
||||
==== Customizing Type Mapping
|
||||
|
||||
If you want to avoid writing the entire Java class name as type information but would rather like to use a key, you can use the `@TypeAlias` annotation on the entity class. If you need to customize the mapping even more, have a look at the `TypeInformationMapper` interface. An instance of that interface can be configured at the `DefaultMongoTypeMapper`, which can, in turn, be configured on `MappingMongoConverter`. The following example shows how to define a type alias for an entity:
|
||||
If you want to avoid writing the entire Java class name as type information but would rather like to use a key, you can use the `@TypeAlias` annotation on the entity class.If you need to customize the mapping even more, have a look at the `TypeInformationMapper` interface.An instance of that interface can be configured at the `DefaultMongoTypeMapper`, which can, in turn, be configured on `MappingMongoConverter`.The following example shows how to define a type alias for an entity:
|
||||
|
||||
.Defining a type alias for an Entity
|
||||
====
|
||||
@@ -718,7 +718,9 @@ Note that the resulting document contains `pers` as the value in the `_class` Fi
|
||||
|
||||
[WARNING]
|
||||
====
|
||||
Type aliases only work if the mapping context is aware of the actual type. The required entity metadata is aquired either on first save or has to be provided via the configurations initial entity set. By default the configuration base package is scanned for potential candidates.
|
||||
Type aliases only work if the mapping context is aware of the actual type.
|
||||
The required entity metadata is determined either on first save or has to be provided via the configurations initial entity set.
|
||||
By default, the configuration class scans the base package for potential candidates.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -968,14 +970,14 @@ Person oldValue = template.update(Person.class)
|
||||
.apply(update)
|
||||
.findAndModifyValue(); // return's old person object
|
||||
|
||||
assertThat(oldValue.getFirstName(), is("Harry"));
|
||||
assertThat(oldValue.getAge(), is(23));
|
||||
assertThat(oldValue.getFirstName()).isEqualTo("Harry");
|
||||
assertThat(oldValue.getAge()).isEqualTo(23);
|
||||
|
||||
Person newValue = template.query(Person.class)
|
||||
.matching(query)
|
||||
.findOneValue();
|
||||
|
||||
assertThat(newValue.getAge(), is(24));
|
||||
assertThat(newValue.getAge()).isEqualTo(24);
|
||||
|
||||
Person newestValue = template.update(Person.class)
|
||||
.matching(query)
|
||||
@@ -983,10 +985,10 @@ Person newestValue = template.update(Person.class)
|
||||
.withOptions(FindAndModifyOptions.options().returnNew(true)) // Now return the newly updated document when updating
|
||||
.findAndModifyValue();
|
||||
|
||||
assertThat(newestValue.getAge(), is(25));
|
||||
assertThat(newestValue.getAge()).isEqualTo(25);
|
||||
----
|
||||
|
||||
The `FindAndModifyOptions` method lets you set the options of `returnNew`, `upsert`, and `remove`. An example extending from the previous code snippet follows:
|
||||
The `FindAndModifyOptions` method lets you set the options of `returnNew`, `upsert`, and `remove`.An example extending from the previous code snippet follows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -996,8 +998,8 @@ Person upserted = template.update(Person.class)
|
||||
.withOptions(FindAndModifyOptions.options().upsert(true).returnNew(true))
|
||||
.findAndModifyValue()
|
||||
|
||||
assertThat(upserted.getFirstName(), is("Mary"));
|
||||
assertThat(upserted.getAge(), is(1));
|
||||
assertThat(upserted.getFirstName()).isEqualTo("Mary");
|
||||
assertThat(upserted.getAge()).isOne();
|
||||
----
|
||||
|
||||
[[mongo-template.aggregation-update]]
|
||||
@@ -1153,7 +1155,7 @@ An `OptimisticLockingFailureException` is raised if a versioned entity cannot be
|
||||
[[mongo.query]]
|
||||
== Querying Documents
|
||||
|
||||
You can use the `Query` and `Criteria` classes to express your queries. They have method names that mirror the native MongoDB operator names, such as `lt`, `lte`, `is`, and others. The `Query` and `Criteria` classes follow a fluent API style so that you can chain together multiple method criteria and queries while having easy-to-understand code. To improve readability, static imports let you avoid using the 'new' keyword for creating `Query` and `Criteria` instances. You can also use `BasicQuery` to create `Query` instances from plain JSON Strings, as shown in the following example:
|
||||
You can use the `Query` and `Criteria` classes to express your queries.They have method names that mirror the native MongoDB operator names, such as `lt`, `lte`, `is`, and others.The `Query` and `Criteria` classes follow a fluent API style so that you can chain together multiple method criteria and queries while having easy-to-understand code.To improve readability, static imports let you avoid using the 'new' keyword for creating `Query` and `Criteria` instances.You can also use `BasicQuery` to create `Query` instances from plain JSON Strings, as shown in the following example:
|
||||
|
||||
.Creating a Query instance from a plain JSON String
|
||||
====
|
||||
@@ -2183,7 +2185,7 @@ mongoOperations.find<Book>(
|
||||
[[mongo.query.additional-query-options]]
|
||||
=== Additional Query Options
|
||||
|
||||
MongoDB offers various ways of applying meta information, like a comment or a batch size, to a query. Using the `Query` API
|
||||
MongoDB offers various ways of applying meta information, like a comment or a batch size, to a query.Using the `Query` API
|
||||
directly there are several methods for those options.
|
||||
|
||||
====
|
||||
@@ -2213,11 +2215,11 @@ include::query-by-example.adoc[leveloffset=+1]
|
||||
[[mongo.query.count]]
|
||||
== Counting Documents
|
||||
|
||||
In pre 3.x versions of SpringData MongoDB the count operation was executed against MongoDBs internal collection statistics.
|
||||
With the introduction of <<mongo.transactions>> this was no longer possible because statistics would not correctly reflect potential changes during a transaction requiring an aggregation based count approach.
|
||||
So in 2.x `MongoOperations.count()` would use the collection statistics if no transaction was in progress, and the aggregation variant if so.
|
||||
In pre-3.x versions of SpringData MongoDB the count operation used MongoDBs internal collection statistics.
|
||||
With the introduction of <<mongo.transactions>> this was no longer possible because statistics would not correctly reflect potential changes during a transaction requiring an aggregation-based count approach.
|
||||
So in version 2.x `MongoOperations.count()` would use the collection statistics if no transaction was in progress, and the aggregation variant if so.
|
||||
|
||||
As off Spring Data MongoDB 3.x any `count` operation, may it be with our without a filter query, uses the aggregation based count approach via MongoDBs `countDocuments`.
|
||||
As of Spring Data MongoDB 3.x any `count` operation uses regardless the existence of filter criteria the aggregation-based count approach via MongoDBs `countDocuments`.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
@@ -2236,7 +2238,7 @@ Therefore a given `Query` will be rewritten for `count` operations using `Reacti
|
||||
<1> Count source query using `$near`.
|
||||
<2> Rewritten query now using `$geoWithin` with `$center`.
|
||||
<3> Count source query using `$near` with `$minDistance` and `$maxDistance`.
|
||||
<4> Rewritten query now a combination of `$nor` `$geowithin` critierias to work aournd unsupported `$minDistance`.
|
||||
<4> Rewritten query now a combination of `$nor` `$geowithin` critierias to work around unsupported `$minDistance`.
|
||||
====
|
||||
|
||||
[[mongo.mapreduce]]
|
||||
@@ -2244,12 +2246,12 @@ Therefore a given `Query` will be rewritten for `count` operations using `Reacti
|
||||
|
||||
You can query MongoDB by using Map-Reduce, which is useful for batch processing, for data aggregation, and for when the query language does not fulfill your needs.
|
||||
|
||||
Spring provides integration with MongoDB's Map-Reduce by providing methods on `MongoOperations` to simplify the creation and execution of Map-Reduce operations. It can convert the results of a Map-Reduce operation to a POJO and integrates with Spring's https://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html#resources[Resource abstraction]. This lets you place your JavaScript files on the file system, classpath, HTTP server, or any other Spring Resource implementation and then reference the JavaScript resources through an easy URI style syntax -- for example, `classpath:reduce.js;`. Externalizing JavaScript code in files is often preferable to embedding them as Java strings in your code. Note that you can still pass JavaScript code as Java strings if you prefer.
|
||||
Spring provides integration with MongoDB's Map-Reduce by providing methods on `MongoOperations` to simplify the creation and execution of Map-Reduce operations.It can convert the results of a Map-Reduce operation to a POJO and integrates with Spring's https://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/core.html#resources[Resource abstraction].This lets you place your JavaScript files on the file system, classpath, HTTP server, or any other Spring Resource implementation and then reference the JavaScript resources through an easy URI style syntax -- for example, `classpath:reduce.js;`.Externalizing JavaScript code in files is often preferable to embedding them as Java strings in your code.Note that you can still pass JavaScript code as Java strings if you prefer.
|
||||
|
||||
[[mongo.mapreduce.example]]
|
||||
=== Example Usage
|
||||
|
||||
To understand how to perform Map-Reduce operations, we use an example from the book, _MongoDB - The Definitive Guide_ footnote:[Kristina Chodorow. _MongoDB - The Definitive Guide_. O'Reilly Media, 2013]. In this example, we create three documents that have the values [a,b], [b,c], and [c,d], respectively. The values in each document are associated with the key, 'x', as the following example shows (assume these documents are in a collection named `jmr1`):
|
||||
To understand how to perform Map-Reduce operations, we use an example from the book, _MongoDB - The Definitive Guide_ footnote:[Kristina Chodorow. _MongoDB - The Definitive Guide_. O'Reilly Media, 2013].In this example, we create three documents that have the values [a,b], [b,c], and [c,d], respectively.The values in each document are associated with the key, 'x', as the following example shows (assume these documents are in a collection named `jmr1`):
|
||||
|
||||
[source]
|
||||
----
|
||||
@@ -2311,7 +2313,7 @@ ValueObject [id=c, value=2.0]
|
||||
ValueObject [id=d, value=1.0]
|
||||
----
|
||||
|
||||
The `MapReduceResults` class implements `Iterable` and provides access to the raw output and timing and count statistics. The following listing shows the `ValueObject` class:
|
||||
The `MapReduceResults` class implements `Iterable` and provides access to the raw output and timing and count statistics.The following listing shows the `ValueObject` class:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -2339,7 +2341,7 @@ public class ValueObject {
|
||||
}
|
||||
----
|
||||
|
||||
By default, the output type of `INLINE` is used so that you need not specify an output collection. To specify additional Map-Reduce options, use an overloaded method that takes an additional `MapReduceOptions` argument. The class `MapReduceOptions` has a fluent API, so adding additional options can be done in a compact syntax. The following example sets the output collection to `jmr1_out` (note that setting only the output collection assumes a default output type of `REPLACE`):
|
||||
By default, the output type of `INLINE` is used so that you need not specify an output collection.To specify additional Map-Reduce options, use an overloaded method that takes an additional `MapReduceOptions` argument.The class `MapReduceOptions` has a fluent API, so adding additional options can be done in a compact syntax.The following example sets the output collection to `jmr1_out` (note that setting only the output collection assumes a default output type of `REPLACE`):
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -2355,7 +2357,7 @@ MapReduceResults<ValueObject> results = mongoOperations.mapReduce("jmr1", "class
|
||||
options().outputCollection("jmr1_out"), ValueObject.class);
|
||||
----
|
||||
|
||||
You can also specify a query to reduce the set of data that is fed into the Map-Reduce operation. The following example removes the document that contains [a,b] from consideration for Map-Reduce operations:
|
||||
You can also specify a query to reduce the set of data that is fed into the Map-Reduce operation.The following example removes the document that contains [a,b] from consideration for Map-Reduce operations:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
|
||||
@@ -6,6 +6,16 @@ The 4.0 MongoDB Java Driver does no longer support certain features that have al
|
||||
Some of the changes affect the initial setup configuration as well as compile/runtime features.
|
||||
We summarized the most typical changes one might encounter.
|
||||
|
||||
Things to keep in mind when using the 4.0 driver:
|
||||
|
||||
* `IndexOperations.resetIndexCache()` is no longer supported.
|
||||
* Any `MapReduceOptions.extraOption` is silently ignored.
|
||||
* `WriteResult` no longer holds error information but, instead, throws an `Exception`.
|
||||
* `MongoOperations.executeInSession(…)` no longer calls `requestStart` and `requestDone`.
|
||||
* Index name generation has become a driver-internal operation.
|
||||
Spring Data MongoDB still uses the 2.x schema to generate names.
|
||||
* Some `Exception` messages differ between the generation 2 and 3 servers as well as between the MMap.v1 and WiredTiger storage engines.
|
||||
|
||||
== Dependency Changes
|
||||
|
||||
Instead of the single artifact uber-jar `mongo-java-driver`, imports are now split to include separate artifacts:
|
||||
|
||||
Reference in New Issue
Block a user