Using Spring Data MongoDB with MongoDB 3.0

The rest of this section describes how to use Spring Data MongoDB with MongoDB 3.0.

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:

<?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 http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
		http://www.springframework.org/schema/beans http://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>

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.

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:

@Configuration
public class ApplicationContextEventTestsAppConfig extends AbstractMongoConfiguration {

  @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:

<?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 http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <mongo:mongo-client credentials="user:password@database" />

</beans>

Server-side Validation

MongoDB supports 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.

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 JSON Schema for further details.

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:

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));
The field names used within the query expression are mapped to the domain types property names, taking potential @Field annotations into account.

Miscellaneous Details

This section covers briefly lists additional things to keep in mind when using the 3.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.