diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java index e824ad4e9..d573a0751 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java @@ -81,7 +81,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery { private String replacePlaceholders(String input, ConvertingParameterAccessor accessor) { Matcher matcher = PLACEHOLDER.matcher(input); - String result = null; + String result = input; while (matcher.find()) { String group = matcher.group(); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java index 7fc787241..1a9ceab5d 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java @@ -84,6 +84,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests { List result = repository.findByThePersonsFirstname("Leroi"); assertThat(result.size(), is(1)); assertThat(result, hasItem(leroi)); + assertThat(result.get(0).getAge(),is(nullValue())); } @Test diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java index 7df25e42b..564a5890c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java @@ -44,7 +44,7 @@ public interface PersonRepository extends MongoRepository, Query * @param firstname * @return */ - @Query("{ 'firstname' : ?0 }") + @Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname': 1, 'lastname': 1}") List findByThePersonsFirstname(String firstname); diff --git a/src/docbkx/index.xml b/src/docbkx/index.xml index 05c4bb800..d0ecd261f 100644 --- a/src/docbkx/index.xml +++ b/src/docbkx/index.xml @@ -62,6 +62,8 @@ + + diff --git a/src/docbkx/reference/cross-store.xml b/src/docbkx/reference/cross-store.xml new file mode 100644 index 000000000..cc96c502a --- /dev/null +++ b/src/docbkx/reference/cross-store.xml @@ -0,0 +1,17 @@ + + + + Cross Store support + + Cross Store support introduction. + + +
+ Cross Store Configuration + + Cross Store... + + +
+
diff --git a/src/docbkx/reference/logging.xml b/src/docbkx/reference/logging.xml new file mode 100644 index 000000000..bed76327d --- /dev/null +++ b/src/docbkx/reference/logging.xml @@ -0,0 +1,17 @@ + + + + Logging support + + Logging support introduction. + + +
+ MongoDB Log4j Configuration + + Log4j... + + +
+
diff --git a/src/docbkx/reference/mongo-repositories.xml b/src/docbkx/reference/mongo-repositories.xml index 0a8de97c8..5299858b2 100644 --- a/src/docbkx/reference/mongo-repositories.xml +++ b/src/docbkx/reference/mongo-repositories.xml @@ -1,70 +1,68 @@ + Mongo repositories - - This chapter will point out the specialties for repository support - for MongoDB. This builds on the core repository support explained in. So make sure you've got a sound understanding - of the basic concepts explained there. - - +
+ Introduction - To access domain entities stored in a MongoDB you can leverage our + This chapter will point out the specialties for repository support + for MongoDB. This builds on the core repository support explained in. So make sure you've got a sound understanding + of the basic concepts explained there. +
+ +
+ Usage + + To access domain entities stored in a MongoDB you can leverage our sophisticated repository support that eases implementing those quite significantly. To do so, simply create an interface for your - repository: - + repository: - - Sample Person entity + + Sample Person entity - public class Person { + public class Person { - private ObjectId id; + private String id; private String firstname; private String lastname; + private Address address; // … getters and setters omitted - } +} - + - We have a quite simple domain object here. Note that it has a property - named - id - of typeObjectId. The default - serialization mechanism used in - MongoTemplate - (which - is backing the repository support) regards properties named id as document - id. Currently we supportString, - ObjectId - and - BigInteger - as - id-types. - + We have a quite simple domain object here. Note that it has a + property named id of typeObjectId. The + default serialization mechanism used in + MongoTemplate (which is backing the repository + support) regards properties named id as document id. Currently we + supportString, ObjectId and + BigInteger as id-types. - - Basic repository interface to persist Person entities + + Basic repository interface to persist Person entities - public interface PersonRepository extends MongoRepository<Person, Long> { + public interface PersonRepository extends MongoRepository<Person, Long> { - } + // additional custom finder methods go here +} - + - The central MongoDB CRUD repository interface is + The central MongoDB CRUD repository interface is MongoRepository. Right now this interface simply serves typing purposes but we will add additional methods to it - later. In your Spring configuration simply add - + later. In your Spring configuration simply add - - General mongo repository Spring configuration + + General mongo repository Spring configuration - <?xml version="1.0" encoding="UTF-8"?> + <?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" @@ -76,117 +74,109 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> - <mongo:repositories base-package="com.acme.*.repositories" - mongo-template-ref="myMongoTemplate" /> + <mongo:mongo id="mongo" /> + + <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> + <constructor-arg ref="mongo" /> + <constructor-arg value="database" /> + <constructor-arg value="collection" /> + <constructor-arg> + <mongo:mapping-converter /> + </constructor-arg> + </bean> - … + <mongo:repositories base-package="com.acme.*.repositories" mongo-template-ref="myMongoTemplate" /> + … - </beans> - +</beans> + - This namespace element will cause the base packages to be scanned for - interfaces extending - MongoRepository - and - create Spring beans for each of them found. By default the repositories will - 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 will cause the base packages to be scanned + for interfaces extending MongoRepository + and create Spring beans for each of them found. By default the + repositories will 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. - - MongoRepository - extends - PagingAndSortingRepository - which you can read - about in. In general 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. So accessing the second page of - Persons at a page size of 10 would simply look - something like this: - + MongoRepository extends + PagingAndSortingRepository which you can + read about in. In general 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. So accessing the + second page of Persons at a page size of 10 would + simply look something like this: - - Paging access to Person entities + + Paging access to Person entities - @RunWith(SpringJUnit4ClassRunner.class) - @ContextConfiguration - class PersonRepositoryTests { + @RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class PersonRepositoryTests { - @Autowired PersonRepository repository; + @Autowired PersonRepository repository; - @Test - public void readsFirstPageCorrectly() { + @Test + public void readsFirstPageCorrectly() { Page<Person> persons = repository.findAll(new PageRequest(0, 10)); assertThat(persons.isFirstPage(), is(true)); - } - } - - + } +} + - The sample creates an application context with Spring's unit test + The sample creates an application context with Spring's unit test support which will perform annotation based dependency injection into test cases. Inside the test method we simply use the repository to query the - datastore. We hand the repository a - PageRequest + datastore. We hand the repository a PageRequest instance that requests the first page of persons at a page size of - 10. - + 10. +
Query methods Most of the data access operations you usually trigger on a - repository result a query being executed against the Mongo databases. - Defining such a query is just a matter of declaring a method on the - repository interface - + repository result a query being executed against the Mongo databases. + Defining such a query is just a matter of declaring a method on the + repository interface PersonRepository with query methods - public interface PersonRepository extends MongoRepository<Person, Long> { + public interface PersonRepository extends MongoRepository<Person, String> { - List<Person> findByLastname(String lastname); + List<Person> findByLastname(String lastname); - Page<Person> findByFirstname(String firstname, Pageable pageable); - } - + Page<Person> findByFirstname(String firstname, Pageable pageable); + + Person findByShippingAddresses(Address address); + +} The first method shows a query for all people with the given - lastname. The query will be derived parsing the method name for - constraints which can be concatenated with - And - and - Or. Thus the method name will result in a query - expression of{"lastname" : lastname}. The second example - shows how pagination is applied to a query. Just equip your method - signature with a - Pageable - parameter and let - the method return a - Page - instance and we - will automatically page the query accordingly. - + lastname. The query will be derived parsing the method name for + constraints which can be concatenated with And and + Or. Thus the method name will result in a query + expression of{"lastname" : lastname}. The second example + shows how pagination is applied to a query. Just equip your method + signature with a Pageable parameter and let + the method return a Page instance and we + will automatically page the query accordingly. The third examples shows + that you can query based on properties which are not a primitive + type. - - +
Supported keywords for query methods - + - + - + @@ -200,133 +190,186 @@ - - GreaterThan - + GreaterThan - - findByAgeGreaterThan(int - age) - - + findByAgeGreaterThan(int age) + - - {"age" : {"$gt" : age}} - + {"age" : {"$gt" : age}} - - LessThan - + LessThan - - findByAgeLessThan(int - age) - - + findByAgeLessThan(int age) + - - {"age" : {"$lt" : age}} - + {"age" : {"$lt" : age}} - - Between - + Between - - findByAgeBetween(int from, int - to) - - + findByAgeBetween(int from, int to) + - - {"age" : {"$gt" : from, "$lt" : to}} - + {"age" : {"$gt" : from, "$lt" : to}} IsNotNull, - NotNull - + NotNull - - findByFirstnameNotNull() - + findByFirstnameNotNull() - - {"age" : {"$ne" : null}} - + {"age" : {"$ne" : null}} IsNull, - Null - + Null - - findByFirstnameNull() - + findByFirstnameNull() - - {"age" : null} - + {"age" : null} - - Like - + Like - - findByFirstnameLike(String - name) - - + findByFirstnameLike(String name) + - - {"age" : age} - ( - age - as - regex) - + {"age" : age} ( age as + regex) (No keyword) - - findByFirstname(String - name) - - + findByFirstname(String name) + - - {"age" : name} - + {"age" : name} - - Not - + Not - - findByFirstnameNot(String - name) - - + findByFirstnameNot(String name) + - - {"age" : {"$ne" : name}} - + {"age" : {"$ne" : name}} -
-
+ + +
+ Mongo JSON based query methods and field restriction + + The annotation + org.springframework.data.document.mongodb.repository.Query can be + applied to finder methods on your repository which allows you to specify + a Mongo JSON string to define the actual query to be executed instead of + infering the query from the method name. For example + + public interface PersonRepository extends MongoRepository<Person, String> + + @Query("{ 'firstname' : ?0 }") + List<Person> findByThePersonsFirstname(String firstname); + +} + + The placeholder ?0 lets you substitue the value from the method + arguments into the JSON query definition. + + You can also use the filter property to define the set of + properties that will be mapped into the Java object. For example, + + + public interface PersonRepository extends MongoRepository<Person, String> + + @Query(value="{ 'firstname' : ?0 }", fields="firstname,lastname") + List<Person> findByThePersonsFirstname(String firstname); + +} +
+ +
+ Type-safe Query methods + + Mongo repository support integrates with the QueryDSL project which provides a + meant to perform type-safe queries (no strings) in Java. To quote from + the project description, "Instead of writing queries as inline strings + or externalizing them into XML files they are constructed via a fluent + API." It provides the following features + + + + Code completion in IDE (all properties, methods and operations + can be expanded in your favorite Java IDE) + + + + Almost no syntactically invalid queries allowed (type-safe on + all levels) + + + + Domain types and properties can be referenced safely (no + Strings involved!) + + + + Adopts better to refactoring changes in domain types + + + + Incremental query definition is easier + + + + This will enable you to write queries as shown below + + QPerson person = new QPerson("person"); +List<Person> result = repository.findAll(person.address.zipCode.eq("C0123")); + + +Page<Person> page = repository.findAll(person.lastname.contains("a"), + new PageRequest(0, 2, Direction.ASC, "lastname")); + + QPerson is a class that is generated (via the Java annotation post + processing tool) which is a Predicate that allows you to write type safe + queries. Notice that there are no strings in the query other than the + value "C0123". + + The use of the generated Predicate class is made available via the + interface QueryDslPredicateExecutor which is shown below + + public interface QueryDslPredicateExecutor<T> { + + T findOne(Predicate predicate); + + List<T> findAll(Predicate predicate); + + List<T> findAll(Predicate predicate, OrderSpecifier<?>... orders); + + Page<T> findAll(Predicate predicate, Pageable pageable); + + Long count(Predicate predicate); +} + + + To use this in your repository implementation, simply inherit from + it as well. This is shown below + + public interface PersonRepository extends MongoRepository<Person, String>, QueryDslPredicateExecutor<Person> { + + // additional finder methods go here + +} +
-
\ No newline at end of file + diff --git a/src/docbkx/reference/mongodb.xml b/src/docbkx/reference/mongodb.xml index 7f1f7877b..5a36b727e 100644 --- a/src/docbkx/reference/mongodb.xml +++ b/src/docbkx/reference/mongodb.xml @@ -5,7 +5,7 @@ MongoDB support The MongoDB support contains a wide range of features which are - summarized below. + summarized below. @@ -84,7 +84,7 @@ Spring MongoDB support requires MongoDB 1.4 or higher and Java SE 5 or higher. The latest production release (1.8.x as of this writing) is - recommended. + recommended.
@@ -247,9 +247,10 @@ public class AppConfig {
-
- Working with objects using the - <classname>MongoTemplate</classname> +
+ Introduction to MongoTemplate + + Most users are likely to use MongoTemplate and its corresponding package @@ -270,6 +271,12 @@ public class AppConfig { MongoTemplate in the context of the Spring container. + Exception Translation + + Mongo Converters + + Execute callbacks +
Instantiating MongoTemplate @@ -401,424 +408,102 @@ public class AppConfig { The default is to use a WriteResultChecking of NONE.
+
+ +
+ Saving, Updating, and Deleting Documents + + Insert, savfe, remove, findAndRemove + +
- Overview of MongoTemplate Methods + Methods for saving documents - The public methods for MongoTemplate are - defined by the interfaceMongoOperations. - They can be grouped into the following categories: + Once we have created the collection and maybe an index we can + start using the collection to store our domain objects as documents. + Note that we are using a static import for + org.springframework.data.document.mongodb.query.Criteria.where + to make the query more readable. -
- Methods for working with a Collection + + Inserting and retrieving documents using the + MongoTemplate - - - Set<String> getCollectionNames () - A set of collection names. - + import static org.springframework.data.document.mongodb.query.Criteria.where; - - boolean collectionExists (String - collectionName) Check to see if a collection with a - given name exists. - + ... - - DBCollection createCollection (String - collectionName) Create an uncapped collection with - the provided name. - + Person p = new Person("Bob", 33); + mongoTemplate.insert("MyCollection", p); - - DBCollection createCollection (String - collectionName, CollectionOptions collectionOptions) - Create a collect with the provided name and options. - + Person qp = mongoTemplate.findOne("MyCollection", + new Query(where("id").is(p.getId())), Person.class); + + - - void dropCollection (String - collectionName) Drop the collection with the given - name. - + + + void save + (Object objectToSave) Save the + object to the default collection. + - - DBCollection getCollection (String - collectionName) Get a collection by name, creating it - if it doesn't exist. - + + void save + (String collectionName, Object objectToSave) + Save the object to the specified collection. + - - DBCollection getDefaultCollection - () The default collection used by this - template. - + + <T> void save + (T objectToSave, MongoWriter<T> writer) + Save the object into the default collection using the + provided writer. + - - String getDefaultCollectionName - () The default collection name used by this - template. - - + + <T> void save + (String collectionName, T objectToSave, + MongoWriter<T> writer) Save the object into the + specified collection using the provided writer. + + - -
+ +
-
- Methods for executing commands +
+ Updating documents in a collection - - - CommandResult executeCommand (DBObject - command) Execute a MongoDB command. - + For updates we can elect to update the first document found using + updateFirst or we can update all documents that were + found to match the query usingupdateMulti. Here is an + example of an update of all SAVINGS accounts where we are adding a one + time $50.00 bonus to the balance using the $inc + operator. - - CommandResult executeCommand (String - jsonCommand) Execute the a MongoDB command expressed - as a JSON string. - + + Updating documents using the MongoTemplate - - <T> T execute - (CollectionCallback<T> action) - Executes the given CollectionCallback on the default - collection. - + import static org.springframework.data.document.mongodb.query.Criteria.where; - - <T> T execute (String collectionName, - CollectionCallback<T> action) Executes the - given CollectionCallback on the collection of the given - name.update using the $addToSet update modifier - + ... - - <T> T execute (DbCallback<T> - action) Executes a DbCallback translating any - exceptions as necessary. - + WriteResult wr = mongoTemplate.updateMulti( + new Query(where("accounts.accountType").is(Account.Type.SAVINGS)), + new Update().inc("accounts.$.balance", 50.00)); + + - - <T> T executeInSession - (DbCallback<T> action) Executes the - given DbCallback within the same connection to the database so - as to ensure consistency in a write heavy environment where you - may read the data that you wrote. - - + In addition to the Query discussed above we + provide the update definition using an Update + object. The Update class has methods that match + the update modifiers available for MongoDB. - -
- -
- Methods for creating an Index - - - - void ensureIndex - (IndexDefinition indexDefintion) - Ensure that an index for the provided IndexDefinition exists for - the default collection. - - - - void ensureIndex - (String collectionName, IndexDefinition - indexSpecification) Ensure that an index for the - provided IndexDefinition exists. - - - - -
- -
- Methods for inserting documents - - - - void insert - (Object objectToSave) Insert the - object into the default collection. - - - - void insert - (String collectionName, Object - objectToSave) Insert the object into the specified - collection. - - - - void insertList - (List<? extends Object> listToSave) - Insert a list of objects into the default collection - in a single batch write to the database. - - - - void insertList - (String collectionName, List<? extends - Object> listToSave) Insert a list of objects into - the specified collection in a single batch write to the - database. - - - - <T> void insert (T objectToSave, - MongoWriter<T> writer) Insert the object into - the default collection. - - - - <T> void insert (String collectionName, - T objectToSave, MongoWriter<T> writer) Insert - the object into the specified collection. - - - - <T> void insertList (List<? extends - T> listToSave, MongoWriter<T> writer) Insert - a list of objects into the default collection using the provided - MongoWriter instance - - - - <T> void insertList (String - collectionName, List<? extends T> listToSave, - MongoWriter<T> writer) Insert a list of objects - into the specified collection using the provided MongoWriter - instance - - - - -
- -
- Methods for querying for documents - - - - <T> List<T> getCollection (Class<T> - targetClass) Query for a list of objects of type T - from the default collection. - - - - <T> List<T> getCollection (String - collectionName, Class<T> targetClass) Query for - a list of objects of type T from the specified - collection. - - - - <T> List<T> getCollection (String - collectionName, Class<T> targetClass, MongoReader<T> - reader) Query for a list of objects of type T from - the specified collection, mapping the DBObject using the - provided MongoReader. - - - - <T> T findOne (Query query, - Class<T> targetClass) Map the results of an - ad-hoc query on the default MongoDB collection to a single - instance of an object of the specified type. - - - - <T> T findOne (Query query, - Class<T> targetClass, MongoReader<T> reader) - Map the results of an ad-hoc query on the default - MongoDB collection to a single instance of an object of the - specified type. - - - - <T> T findOne (String collectionName, - Query query, Class<T> targetClass) Map the - results of an ad-hoc query on the specified collection to a - single instance of an object of the specified type. - - - - <T> T findOne (String collectionName, - Query query, Class<T> targetClass, MongoReader<T> - reader) Map the results of an ad-hoc query on the - specified collection to a single instance of an object of the - specified type. - - - - <T> List<T> find (Query query, - Class<T> targetClass) Map the results of an - ad-hoc query on the default MongoDB collection to a List of the - specified type. - - - - <T> List<T> find (Query query, - Class<T> targetClass, MongoReader<T> reader) - Map the results of an ad-hoc query on the default - MongoDB collection to a List of the specified type. - - - - <T> List<T> find (String collectionName, - Query query, Class<T> targetClass) Map the - results of an ad-hoc query on the specified collection to a List - of the specified type. - - - - <T> List<T> find (String collectionName, - Query query, Class<T> targetClass, CursorPreparer - preparer) Map the results of an ad-hoc query on the - specified collection to a List of the specified type. - - - - <T> List<T> find (String collectionName, - Query query, Class<T> targetClass, MongoReader<T> - reader) Map the results of an ad-hoc query on the - specified collection to a List of the specified type. - - - - <T> T findAndRemove (Query query, - Class<T> targetClass) Map the results of an - ad-hoc query on the default MongoDB collection to a single - instance of an object of the specified type. The first document - that matches the query is returned and also removed from the - collection in the database. - - - - <T> T findAndRemove (Query query, - Class<T> targetClass, MongoReader<T> reader) - Map the results of an ad-hoc query on the default - MongoDB collection to a single instance of an object of the - specified type. The first document that matches the query is - returned and also removed from the collection in the - database. - - - - <T> T findAndRemove (String - collectionName, Query query, Class<T> targetClass) - Map the results of an ad-hoc query on the specified - collection to a single instance of an object of the specified - type. The first document that matches the query is returned and - also removed from the collection in the database. - - - - <T> T findAndRemove (String - collectionName, Query query, Class<T> targetClass, - MongoReader<T> reader) Map the results of an - ad-hoc query on the specified collection to a single instance of - an object of the specified type. The first document that matches - the query is returned and also removed from the collection in - the database. - - - - -
- -
- Methods for saving documents - - - - void save - (Object objectToSave) Save the - object to the default collection. - - - - void save - (String collectionName, Object - objectToSave) Save the object to the specified - collection. - - - - <T> void save (T objectToSave, - MongoWriter<T> writer) Save the object into the - default collection using the provided writer. - - - - <T> void save (String collectionName, T - objectToSave, MongoWriter<T> writer) Save the - object into the specified collection using the provided - writer. - - - - -
- -
- Methods for removing documents - - - - void remove - (Query query) Remove all - documents from the default collection that match the provided - query document criteria. - - - - void remove - (String collectionName, Query query) - Remove all documents from the specified collection - that match the provided query document criteria. - - - - -
+ As you can see most methods return the + Update object to provide a fluent style for the + API.
Methods for executing updates for documents @@ -861,69 +546,178 @@ public class AppConfig {
+ +
+ Methods for the Update class + + + + Update addToSet + (String key, Object value) + Update using the $addToSet update + modifier + + + + Update inc + (String key, Number inc) Update + using the $inc update modifier + + + + Update pop + (String key, Update.Position pos) + Update using the $pop update + modifier + + + + Update pull + (String key, Object value) + Update using the $pull update modifier + + + + Update pullAll + (String key, Object[] values) + Update using the $pullAll update + modifier + + + + Update push + (String key, Object value) + Update using the $push update modifier + + + + Update pushAll + (String key, Object[] values) + Update using the $pushAll update + modifier + + + + Update rename + (String oldName, String newName) + Update using the $rename update + modifier + + + + Update set + (String key, Object value) + Update using the $set update modifier + + + + Update unset + (String key) Update using the + $unset update modifier + + + + +
-
- Working with collections +
+ Methods for inserting documents - It's time to look at some code examples showing how to use the - MongoTemplate. First we look at creating our - first collection. + + + void insert + (Object objectToSave) Insert the + object into the default collection. + - - Working with collections using the MongoTemplate + + void insert + (String collectionName, Object objectToSave) + Insert the object into the specified collection. + - DBCollection collection = null; - if (!mongoTemplate.getCollectionNames().contains("MyNewCollection")) { - collection = mongoTemplate.createCollection("MyNewCollection"); - } + + void insertList + (List<? extends Object> listToSave) + Insert a list of objects into the default collection in + a single batch write to the database. + - mongoTemplate.dropCollection("MyNewCollection"); - - + + void insertList + (String collectionName, List<? extends + Object> listToSave) Insert a list of objects into + the specified collection in a single batch write to the + database. + + + + <T> void insert (T objectToSave, + MongoWriter<T> writer) Insert the object into the + default collection. + + + + <T> void insert (String collectionName, T + objectToSave, MongoWriter<T> writer) Insert the + object into the specified collection. + + + + <T> void insertList (List<? extends + T> listToSave, MongoWriter<T> writer) Insert a + list of objects into the default collection using the provided + MongoWriter instance + + + + <T> void insertList (String + collectionName, List<? extends T> listToSave, + MongoWriter<T> writer) Insert a list of objects + into the specified collection using the provided MongoWriter + instance + + + +
-
- Creating an index +
+ Methods for removing documents - We can create an index on a collection to improve query - performance. + + + void remove + (Query query) Remove all documents + from the default collection that match the provided query document + criteria. + - - Creating an index using the MongoTemplate + + void remove + (String collectionName, Query query) + Remove all documents from the specified collection that + match the provided query document criteria. + + - mongoTemplate.ensureIndex("MyCollection", new Index().on("name", - Order.ASCENDING)); - - +
+
-
- Saving and retrieving objects as documents in a - collection +
+ Querying Documents - Once we have created the collection and maybe an index we can - start using the collection to store our domain objects as documents. - Note that we are using a static import for - org.springframework.data.document.mongodb.query.Criteria.where - to make the query more readable. + Query, Criteria - - Inserting and retrieving documents using the - MongoTemplate + - import static org.springframework.data.document.mongodb.query.Criteria.where; - - ... - - Person p = new Person("Bob", 33); - mongoTemplate.insert("MyCollection", p); - - Person qp = mongoTemplate.findOne("MyCollection", - new Query(where("id").is(p.getId())), Person.class); - - -
+ GeoSpatial Queries
Querying documents in a collection @@ -1125,121 +919,337 @@ public class AppConfig {
-
- Updating documents in a collection +
+ Methods for querying for documents - For updates we can elect to update the first document found using - updateFirst or we can update all documents that were - found to match the query usingupdateMulti. Here is an - example of an update of all SAVINGS accounts where we are adding a one - time $50.00 bonus to the balance using the $inc - operator. + + + <T> List<T> getCollection (Class<T> + targetClass) Query for a list of objects of type T from + the default collection. + - - Updating documents using the MongoTemplate + + <T> List<T> getCollection (String + collectionName, Class<T> targetClass) Query for a + list of objects of type T from the specified collection. + - import static org.springframework.data.document.mongodb.query.Criteria.where; + + <T> List<T> getCollection (String + collectionName, Class<T> targetClass, MongoReader<T> + reader) Query for a list of objects of type T from the + specified collection, mapping the DBObject using the provided + MongoReader. + - ... + + <T> T findOne + (Query query, Class<T> targetClass) + Map the results of an ad-hoc query on the default + MongoDB collection to a single instance of an object of the + specified type. + - WriteResult wr = mongoTemplate.updateMulti( - new Query(where("accounts.accountType").is(Account.Type.SAVINGS)), - new Update().inc("accounts.$.balance", 50.00)); - - + + <T> T findOne + (Query query, Class<T> targetClass, + MongoReader<T> reader) Map the results of an + ad-hoc query on the default MongoDB collection to a single + instance of an object of the specified type. + - In addition to the Query discussed above we - provide the update definition using an Update - object. The Update class has methods that match - the update modifiers available for MongoDB. + + <T> T findOne + (String collectionName, Query query, + Class<T> targetClass) Map the results of an + ad-hoc query on the specified collection to a single instance of + an object of the specified type. + - As you can see most methods return the - Update object to provide a fluent style for the - API. + + <T> T findOne + (String collectionName, Query query, + Class<T> targetClass, MongoReader<T> reader) + Map the results of an ad-hoc query on the specified + collection to a single instance of an object of the specified + type. + -
- Methods for the Update class + + <T> List<T> find (Query query, Class<T> + targetClass) Map the results of an ad-hoc query on the + default MongoDB collection to a List of the specified type. + - - - Update addToSet - (String key, Object value) - Update using the $addToSet update - modifier - + + <T> List<T> find (Query query, Class<T> + targetClass, MongoReader<T> reader) Map the + results of an ad-hoc query on the default MongoDB collection to a + List of the specified type. + - - Update inc - (String key, Number inc) Update - using the $inc update modifier - + + <T> List<T> find (String collectionName, + Query query, Class<T> targetClass) Map the + results of an ad-hoc query on the specified collection to a List + of the specified type. + - - Update pop - (String key, Update.Position pos) - Update using the $pop update - modifier - + + <T> List<T> find (String collectionName, + Query query, Class<T> targetClass, CursorPreparer preparer) + Map the results of an ad-hoc query on the specified + collection to a List of the specified type. + - - Update pull - (String key, Object value) - Update using the $pull update modifier - + + <T> List<T> find (String collectionName, + Query query, Class<T> targetClass, MongoReader<T> + reader) Map the results of an ad-hoc query on the + specified collection to a List of the specified type. + - - Update pullAll - (String key, Object[] values) - Update using the $pullAll update - modifier - + + <T> T findAndRemove (Query query, + Class<T> targetClass) Map the results of an + ad-hoc query on the default MongoDB collection to a single + instance of an object of the specified type. The first document + that matches the query is returned and also removed from the + collection in the database. + - - Update push - (String key, Object value) - Update using the $push update modifier - + + <T> T findAndRemove (Query query, + Class<T> targetClass, MongoReader<T> reader) + Map the results of an ad-hoc query on the default + MongoDB collection to a single instance of an object of the + specified type. The first document that matches the query is + returned and also removed from the collection in the + database. + - - Update pushAll - (String key, Object[] values) - Update using the $pushAll update - modifier - + + <T> T findAndRemove (String + collectionName, Query query, Class<T> targetClass) + Map the results of an ad-hoc query on the specified + collection to a single instance of an object of the specified + type. The first document that matches the query is returned and + also removed from the collection in the database. + - - Update rename - (String oldName, String newName) - Update using the $rename update - modifier - + + <T> T findAndRemove (String + collectionName, Query query, Class<T> targetClass, + MongoReader<T> reader) Map the results of an + ad-hoc query on the specified collection to a single instance of + an object of the specified type. The first document that matches + the query is returned and also removed from the collection in the + database. + + - - Update set - (String key, Object value) - Update using the $set update modifier - + +
- - Update unset - (String key) Update using the - $unset update modifier - -
+
+ GeoSpatial Queries - -
+
-
- Road map ahead +
+ Index and Collection managment - The Spring Data Document projects MongoDB support is in its early - stages. We are interested in feedback, knowing what your use cases are, - what are the common patters you encounter so that the MongoDB module - better serves your needs. Do contact us using the channels mentioned above, we are - interested in hearing from you! + index + + collection + +
+ Methods for creating an Index + + We can create an index on a collection to improve query + performance. + + + Creating an index using the MongoTemplate + + mongoTemplate.ensureIndex("MyCollection", new Index().on("name", + Order.ASCENDING)); + + + + + + void ensureIndex + (IndexDefinition indexDefintion) + Ensure that an index for the provided IndexDefinition exists for + the default collection. + + + + void ensureIndex + (String collectionName, IndexDefinition + indexSpecification) Ensure that an index for the + provided IndexDefinition exists. + + + + +
+ +
+ Methods for working with a Collection + + It's time to look at some code examples showing how to use the + MongoTemplate. First we look at creating our + first collection. + + + Working with collections using the MongoTemplate + + DBCollection collection = null; + if (!mongoTemplate.getCollectionNames().contains("MyNewCollection")) { + collection = mongoTemplate.createCollection("MyNewCollection"); + } + + mongoTemplate.dropCollection("MyNewCollection"); + + + + + + Set<String> getCollectionNames () A + set of collection names. + + + + boolean collectionExists (String + collectionName) Check to see if a collection with a + given name exists. + + + + DBCollection createCollection (String + collectionName) Create an uncapped collection with the + provided name. + + + + DBCollection createCollection (String + collectionName, CollectionOptions collectionOptions) + Create a collect with the provided name and options. + + + + void dropCollection + (String collectionName) Drop the + collection with the given name. + + + + DBCollection getCollection (String + collectionName) Get a collection by name, creating it + if it doesn't exist. + + + + DBCollection getDefaultCollection () + The default collection used by this template. + + + + String getDefaultCollectionName + () The default collection name used by this + template. + + + + +
+
+ +
+ Executing Commands + + exec plain old JS. + +
+ Methods for executing commands + + + + CommandResult executeCommand (DBObject command) + Execute a MongoDB command. + + + + CommandResult executeCommand (String + jsonCommand) Execute the a MongoDB command expressed as + a JSON string. + + + + <T> T execute + (CollectionCallback<T> action) + Executes the given CollectionCallback on the default + collection. + + + + <T> T execute + (String collectionName, + CollectionCallback<T> action) Executes the given + CollectionCallback on the collection of the given name.update + using the $addToSet update modifier + + + + <T> T execute + (DbCallback<T> action) + Executes a DbCallback translating any exceptions as + necessary. + + + + <T> T executeInSession + (DbCallback<T> action) Executes the + given DbCallback within the same connection to the database so as + to ensure consistency in a write heavy environment where you may + read the data that you wrote. + + + + +
+
+ +
+ Lifecycle Events + + The lifecycle events are....