Spring Data Document

org.springframework.data.mongodb.core
Class MongoTemplate

java.lang.Object
  extended by org.springframework.data.mongodb.core.MongoTemplate
All Implemented Interfaces:
Aware, ApplicationContextAware, MongoOperations

public class MongoTemplate
extends Object
implements MongoOperations, ApplicationContextAware

Primary implementation of MongoOperations.

Author:
Thomas Risberg, Graeme Rocher, Mark Pollack, Oliver Gierke

Constructor Summary
MongoTemplate(MongoDbFactory mongoDbFactory)
          Constructor used for a basic template configuration
MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter)
          Constructor used for a basic template configuration.
MongoTemplate(Mongo mongo, String databaseName)
          Constructor used for a basic template configuration
MongoTemplate(Mongo mongo, String databaseName, org.springframework.data.authentication.UserCredentials userCredentials)
          Constructor used for a template configuration with user credentials in the form of UserCredentials
 
Method Summary
<T> boolean
collectionExists(Class<T> entityClass)
          Check to see if a collection with a name indicated by the entity class exists.
 boolean collectionExists(String collectionName)
          Check to see if a collection with a given name exists.
protected  DBObject convertToDbObject(CollectionOptions collectionOptions)
           
 long count(Query query, Class<?> entityClass)
          Returns the number of documents for the given Query by querying the collection of the given entity class.
 long count(Query query, String collectionName)
          Returns the number of documents for the given Query querying the given collection.
<T> DBCollection
createCollection(Class<T> entityClass)
          Create an uncapped collection with a name based on the provided entity class.
<T> DBCollection
createCollection(Class<T> entityClass, CollectionOptions collectionOptions)
          Create a collect with a name based on the provided entity class using the options.
 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.
protected  DBCollection doCreateCollection(String collectionName, DBObject collectionOptions)
          Create the specified collection using the provided options
protected
<S,T> List<T>
doFind(String collectionName, DBObject query, DBObject fields, Class<S> entityClass, org.springframework.data.mongodb.core.CursorPreparer preparer, org.springframework.data.mongodb.core.MongoTemplate.DbObjectCallback<T> objectCallback)
           
protected
<T> List<T>
doFind(String collectionName, DBObject query, DBObject fields, Class<T> entityClass)
          Map the results of an ad-hoc query on the default MongoDB collection to a List using the template's converter.
protected
<T> List<T>
doFind(String collectionName, DBObject query, DBObject fields, Class<T> entityClass, org.springframework.data.mongodb.core.CursorPreparer preparer)
          Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.
protected
<T> T
doFindAndModify(String collectionName, DBObject query, DBObject fields, DBObject sort, Class<T> entityClass, Update update, FindAndModifyOptions options)
           
protected
<T> T
doFindAndRemove(String collectionName, DBObject query, DBObject fields, DBObject sort, Class<T> entityClass)
          Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter.
protected
<T> T
doFindOne(String collectionName, DBObject query, DBObject fields, Class<T> entityClass)
          Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter

The query document is specified as a standard DBObject and so is the fields specification.

protected
<T> void
doInsert(String collectionName, T objectToSave, MongoWriter<T> writer)
           
protected
<T> void
doInsertAll(Collection<? extends T> listToSave, MongoWriter<T> writer)
           
protected
<T> void
doInsertBatch(String collectionName, Collection<? extends T> batchToSave, MongoWriter<T> writer)
           
protected
<T> void
doRemove(String collectionName, Query query, Class<T> entityClass)
           
protected
<T> void
doSave(String collectionName, T objectToSave, MongoWriter<T> writer)
           
protected  WriteResult doUpdate(String collectionName, Query query, Update update, Class<?> entityClass, boolean upsert, boolean multi)
           
<T> void
dropCollection(Class<T> entityClass)
          Drop the collection with the name indicated by the entity class.
 void dropCollection(String collectionName)
          Drop the collection with the given name.
protected  void ensureNotIterable(Object o)
           
<T> T
execute(Class<?> entityClass, CollectionCallback<T> callback)
          Executes the given CollectionCallback on the entity collection of the specified class.
<T> T
execute(DbCallback<T> action)
          Executes a DbCallback translating any exceptions as necessary.
<T> T
execute(String collectionName, CollectionCallback<T> callback)
          Executes the given CollectionCallback on the collection of the given name.
 CommandResult executeCommand(DBObject command)
          Execute a MongoDB command.
 CommandResult executeCommand(DBObject command, int options)
          Execute a MongoDB command.
 CommandResult executeCommand(String jsonCommand)
          Execute the a MongoDB command expressed as a JSON string.
<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.
 void executeQuery(Query query, String collectionName, DocumentCallbackHandler dch)
          Execute a MongoDB query and iterate over the query results on a per-document basis with a DocumentCallbackHandler.
protected  void executeQuery(Query query, String collectionName, DocumentCallbackHandler dch, org.springframework.data.mongodb.core.CursorPreparer preparer)
          Execute a MongoDB query and iterate over the query results on a per-document basis with a DocumentCallbackHandler using the provided CursorPreparer.
<T> List<T>
find(Query query, Class<T> entityClass)
          Map the results of an ad-hoc query on the collection for the entity class to a List of the specified type.
<T> List<T>
find(Query query, Class<T> entityClass, String collectionName)
          Map the results of an ad-hoc query on the specified collection to a List of the specified type.
<T> List<T>
findAll(Class<T> entityClass)
          Query for a list of objects of type T from the collection used by the entity class.
<T> List<T>
findAll(Class<T> entityClass, String collectionName)
          Query for a list of objects of type T from the specified collection.
<T> T
findAndModify(Query query, Update update, Class<T> entityClass)
           
<T> T
findAndModify(Query query, Update update, Class<T> entityClass, String collectionName)
           
<T> T
findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass)
           
<T> T
findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass, String collectionName)
           
<T> T
findAndRemove(Query query, Class<T> entityClass)
          Map the results of an ad-hoc query on the collection for the entity type to a single instance of an object of the specified type.
<T> T
findAndRemove(Query query, Class<T> entityClass, String collectionName)
          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
findById(Object id, Class<T> entityClass)
          Returns a document with the given id mapped onto the given class.
<T> T
findById(Object id, Class<T> entityClass, String collectionName)
          Returns the document with the given id from the given collection mapped onto the given target class.
<T> T
findOne(Query query, Class<T> entityClass)
          Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the specified type.
<T> T
findOne(Query query, Class<T> entityClass, String collectionName)
          Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type.
<T> GeoResults<T>
geoNear(NearQuery near, Class<T> entityClass)
          Returns GeoResult for all entities matching the given NearQuery.
<T> GeoResults<T>
geoNear(NearQuery near, Class<T> entityClass, String collectionName)
          Returns GeoResult for all entities matching the given NearQuery.
 DBCollection getCollection(String collectionName)
          Get a collection by name, creating it if it doesn't exist.
 String getCollectionName(Class<?> entityClass)
          The collection name used for the specified class by this template.
 Set<String> getCollectionNames()
          A set of collection names.
 MongoConverter getConverter()
          Returns the default org.springframework.data.mongodb.core.core.convert.MongoConverter.
 DB getDb()
           
<T> GroupByResults<T>
group(Criteria criteria, String inputCollectionName, GroupBy groupBy, Class<T> entityClass)
          Execute a group operation restricting the rows to those which match the provided Criteria.
<T> GroupByResults<T>
group(String inputCollectionName, GroupBy groupBy, Class<T> entityClass)
          Execute a group operation over the entire collection.
protected  void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation)
          Checks and handles any errors.
 IndexOperations indexOps(Class<?> entityClass)
          Returns the operations that can be performed on indexes
 IndexOperations indexOps(String collectionName)
          Returns the operations that can be performed on indexes
 void insert(Collection<? extends Object> batchToSave, Class<?> entityClass)
          Insert a Collection of objects into a collection in a single batch write to the database.
 void insert(Collection<? extends Object> batchToSave, String collectionName)
          Insert a list of objects into the specified collection in a single batch write to the database.
 void insert(Object objectToSave)
          Insert the object into the collection for the entity type of the object to save.
 void insert(Object objectToSave, String collectionName)
          Insert the object into the specified collection.
 void insertAll(Collection<? extends Object> objectsToSave)
          Insert a mixed Collection of objects into a database collection determining the collection name to use based on the class.
protected  Object insertDBObject(String collectionName, DBObject dbDoc, Class<?> entityClass)
           
protected  List<ObjectId> insertDBObjectList(String collectionName, List<DBObject> dbDocList)
           
protected  void logCommandExecutionError(DBObject command, CommandResult result)
           
<T> MapReduceResults<T>
mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, Class<T> entityClass)
          Execute a map-reduce operation that takes a query.
<T> MapReduceResults<T>
mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, MapReduceOptions mapReduceOptions, Class<T> entityClass)
          Execute a map-reduce operation that takes a query and additional map-reduce options
<T> MapReduceResults<T>
mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, Class<T> entityClass)
          Execute a map-reduce operation.
<T> MapReduceResults<T>
mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, MapReduceOptions mapReduceOptions, Class<T> entityClass)
          Execute a map-reduce operation that takes additional map-reduce options.
protected
<T> void
maybeEmitEvent(MongoMappingEvent<T> event)
           
protected  void populateIdIfNecessary(Object savedObject, Object id)
          Populates the id property of the saved object, if it's not set already.
protected  void prepareCollection(DBCollection collection)
          Prepare the collection before any processing is done using it.
protected  WriteConcern prepareWriteConcern(MongoAction mongoAction)
          Prepare the WriteConcern before any processing is done using it.
 void remove(Object object)
          Remove the given object from the collection by id.
 void remove(Object object, String collection)
          Removes the given object from the given collection.
<T> void
remove(Query query, Class<T> entityClass)
          Remove all documents that match the provided query document criteria from the the collection used to store the entityClass.
 void remove(Query query, String collectionName)
          Remove all documents from the specified collection that match the provided query document criteria.
protected  String replaceWithResourceIfNecessary(String function)
           
 void save(Object objectToSave)
          Save the object to the collection for the entity type of the object to save.
 void save(Object objectToSave, String collectionName)
          Save the object to the specified collection.
protected  Object saveDBObject(String collectionName, DBObject dbDoc, Class<?> entityClass)
           
 void setApplicationContext(ApplicationContext applicationContext)
           
 void setReadPreference(ReadPreference readPreference)
          Used by @{link prepareCollection(DBCollection) to set the ReadPreference before any operations are performed.
 void setWriteConcern(WriteConcern writeConcern)
          Configures the WriteConcern to be used with the template.
 void setWriteConcernResolver(WriteConcernResolver writeConcernResolver)
          Configures the WriteConcernResolver to be used with the template.
 void setWriteResultChecking(WriteResultChecking resultChecking)
          Configures the WriteResultChecking to be used with the template.
 WriteResult updateFirst(Query query, Update update, Class<?> entityClass)
          Updates the first object that is found in the collection of the entity class that matches the query document with the provided update document.
 WriteResult updateFirst(Query query, Update update, String collectionName)
          Updates the first object that is found in the specified collection that matches the query document criteria with the provided updated document.
 WriteResult updateMulti(Query query, Update update, Class<?> entityClass)
          Updates all objects that are found in the collection for the entity class that matches the query document criteria with the provided updated document.
 WriteResult updateMulti(Query query, Update update, String collectionName)
          Updates all objects that are found in the specified collection that matches the query document criteria with the provided updated document.
 WriteResult upsert(Query query, Update update, Class<?> entityClass)
          Performs an upsert.
 WriteResult upsert(Query query, Update update, String collectionName)
          Performs an upsert.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

MongoTemplate

public MongoTemplate(Mongo mongo,
                     String databaseName)
Constructor used for a basic template configuration

Parameters:
mongo -
databaseName -

MongoTemplate

public MongoTemplate(Mongo mongo,
                     String databaseName,
                     org.springframework.data.authentication.UserCredentials userCredentials)
Constructor used for a template configuration with user credentials in the form of UserCredentials

Parameters:
mongo -
databaseName -
userCredentials -

MongoTemplate

public MongoTemplate(MongoDbFactory mongoDbFactory)
Constructor used for a basic template configuration

Parameters:
mongoDbFactory -

MongoTemplate

public MongoTemplate(MongoDbFactory mongoDbFactory,
                     MongoConverter mongoConverter)
Constructor used for a basic template configuration.

Parameters:
mongoDbFactory -
mongoConverter -
Method Detail

setWriteResultChecking

public void setWriteResultChecking(WriteResultChecking resultChecking)
Configures the WriteResultChecking to be used with the template. Setting null will reset the default of .

Parameters:
resultChecking -

setWriteConcern

public void setWriteConcern(WriteConcern writeConcern)
Configures the WriteConcern to be used with the template.

Parameters:
writeConcern -

setWriteConcernResolver

public void setWriteConcernResolver(WriteConcernResolver writeConcernResolver)
Configures the WriteConcernResolver to be used with the template.

Parameters:
writeConcernResolver -

setReadPreference

public void setReadPreference(ReadPreference readPreference)
Used by @{link prepareCollection(DBCollection) to set the ReadPreference before any operations are performed.

Parameters:
readPreference -

setApplicationContext

public void setApplicationContext(ApplicationContext applicationContext)
                           throws BeansException
Specified by:
setApplicationContext in interface ApplicationContextAware
Throws:
BeansException

getConverter

public MongoConverter getConverter()
Returns the default org.springframework.data.mongodb.core.core.convert.MongoConverter.

Specified by:
getConverter in interface MongoOperations
Returns:

getCollectionName

public String getCollectionName(Class<?> entityClass)
Description copied from interface: MongoOperations
The collection name used for the specified class by this template.

Specified by:
getCollectionName in interface MongoOperations
Parameters:
entityClass - must not be null.
Returns:

executeCommand

public CommandResult executeCommand(String jsonCommand)
Description copied from interface: MongoOperations
Execute the a MongoDB command expressed as a JSON string. This will call the method JSON.parse that is part of the MongoDB driver to convert the JSON string to a DBObject. Any errors that result from executing this command will be converted into Spring's DAO exception hierarchy.

Specified by:
executeCommand in interface MongoOperations
Parameters:
jsonCommand - a MongoDB command expressed as a JSON string.

executeCommand

public CommandResult executeCommand(DBObject command)
Description copied from interface: MongoOperations
Execute a MongoDB command. Any errors that result from executing this command will be converted into Spring's DAO exception hierarchy.

Specified by:
executeCommand in interface MongoOperations
Parameters:
command - a MongoDB command

executeCommand

public CommandResult executeCommand(DBObject command,
                                    int options)
Description copied from interface: MongoOperations
Execute a MongoDB command. Any errors that result from executing this command will be converted into Spring's DAO exception hierarchy.

Specified by:
executeCommand in interface MongoOperations
Parameters:
command - a MongoDB command
options - query options to use

logCommandExecutionError

protected void logCommandExecutionError(DBObject command,
                                        CommandResult result)

executeQuery

public void executeQuery(Query query,
                         String collectionName,
                         DocumentCallbackHandler dch)
Description copied from interface: MongoOperations
Execute a MongoDB query and iterate over the query results on a per-document basis with a DocumentCallbackHandler.

Specified by:
executeQuery in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
collectionName - name of the collection to retrieve the objects from
dch - the handler that will extract results, one document at a time

executeQuery

protected void executeQuery(Query query,
                            String collectionName,
                            DocumentCallbackHandler dch,
                            org.springframework.data.mongodb.core.CursorPreparer preparer)
Execute a MongoDB query and iterate over the query results on a per-document basis with a DocumentCallbackHandler using the provided CursorPreparer.

Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification, must not be null.
collectionName - name of the collection to retrieve the objects from
dch - the handler that will extract results, one document at a time
preparer - allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and so on).

execute

public <T> T execute(DbCallback<T> action)
Description copied from interface: MongoOperations
Executes a DbCallback translating any exceptions as necessary.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
action - callback object that specifies the MongoDB actions to perform on the passed in DB instance.
Returns:
a result object returned by the action or null

execute

public <T> T execute(Class<?> entityClass,
                     CollectionCallback<T> callback)
Description copied from interface: MongoOperations
Executes the given CollectionCallback on the entity collection of the specified class.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
entityClass - class that determines the collection to use
callback - callback object that specifies the MongoDB action
Returns:
a result object returned by the action or null

execute

public <T> T execute(String collectionName,
                     CollectionCallback<T> callback)
Description copied from interface: MongoOperations
Executes the given CollectionCallback on the collection of the given name.

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
execute in interface MongoOperations
Type Parameters:
T - return type
Parameters:
collectionName - the name of the collection that specifies which DBCollection instance will be passed into
callback - callback object that specifies the MongoDB action the callback action.
Returns:
a result object returned by the action or null

executeInSession

public <T> T executeInSession(DbCallback<T> action)
Description copied from interface: MongoOperations
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. See the comments on Java Driver Concurrency

Allows for returning a result object, that is a domain object or a collection of domain objects.

Specified by:
executeInSession in interface MongoOperations
Type Parameters:
T - return type
Parameters:
action - callback that specified the MongoDB actions to perform on the DB instance
Returns:
a result object returned by the action or null

createCollection

public <T> DBCollection createCollection(Class<T> entityClass)
Description copied from interface: MongoOperations
Create an uncapped collection with a name based on the provided entity class.

Specified by:
createCollection in interface MongoOperations
Parameters:
entityClass - class that determines the collection to create
Returns:
the created collection

createCollection

public <T> DBCollection createCollection(Class<T> entityClass,
                                         CollectionOptions collectionOptions)
Description copied from interface: MongoOperations
Create a collect with a name based on the provided entity class using the options.

Specified by:
createCollection in interface MongoOperations
Parameters:
entityClass - class that determines the collection to create
collectionOptions - options to use when creating the collection.
Returns:
the created collection

createCollection

public DBCollection createCollection(String collectionName)
Description copied from interface: MongoOperations
Create an uncapped collection with the provided name.

Specified by:
createCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
the created collection

createCollection

public DBCollection createCollection(String collectionName,
                                     CollectionOptions collectionOptions)
Description copied from interface: MongoOperations
Create a collect with the provided name and options.

Specified by:
createCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
collectionOptions - options to use when creating the collection.
Returns:
the created collection

getCollection

public DBCollection getCollection(String collectionName)
Description copied from interface: MongoOperations
Get a collection by name, creating it if it doesn't exist.

Translate any exceptions as necessary.

Specified by:
getCollection in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
an existing collection or a newly created one.

collectionExists

public <T> boolean collectionExists(Class<T> entityClass)
Description copied from interface: MongoOperations
Check to see if a collection with a name indicated by the entity class exists.

Translate any exceptions as necessary.

Specified by:
collectionExists in interface MongoOperations
Parameters:
entityClass - class that determines the name of the collection
Returns:
true if a collection with the given name is found, false otherwise.

collectionExists

public boolean collectionExists(String collectionName)
Description copied from interface: MongoOperations
Check to see if a collection with a given name exists.

Translate any exceptions as necessary.

Specified by:
collectionExists in interface MongoOperations
Parameters:
collectionName - name of the collection
Returns:
true if a collection with the given name is found, false otherwise.

dropCollection

public <T> void dropCollection(Class<T> entityClass)
Description copied from interface: MongoOperations
Drop the collection with the name indicated by the entity class.

Translate any exceptions as necessary.

Specified by:
dropCollection in interface MongoOperations
Parameters:
entityClass - class that determines the collection to drop/delete.

dropCollection

public void dropCollection(String collectionName)
Description copied from interface: MongoOperations
Drop the collection with the given name.

Translate any exceptions as necessary.

Specified by:
dropCollection in interface MongoOperations
Parameters:
collectionName - name of the collection to drop/delete.

indexOps

public IndexOperations indexOps(String collectionName)
Description copied from interface: MongoOperations
Returns the operations that can be performed on indexes

Specified by:
indexOps in interface MongoOperations
Returns:
index operations on the named collection

indexOps

public IndexOperations indexOps(Class<?> entityClass)
Description copied from interface: MongoOperations
Returns the operations that can be performed on indexes

Specified by:
indexOps in interface MongoOperations
Returns:
index operations on the named collection associated with the given entity class

findOne

public <T> T findOne(Query query,
                     Class<T> entityClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findOne in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
Returns:
the converted object

findOne

public <T> T findOne(Query query,
                     Class<T> entityClass,
                     String collectionName)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findOne in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
collectionName - name of the collection to retrieve the objects from
Returns:
the converted object

find

public <T> List<T> find(Query query,
                        Class<T> entityClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the collection for the entity class to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
find in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
Returns:
the List of converted objects

find

public <T> List<T> find(Query query,
                        Class<T> entityClass,
                        String collectionName)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the specified collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
find in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
collectionName - name of the collection to retrieve the objects from
Returns:
the List of converted objects

findById

public <T> T findById(Object id,
                      Class<T> entityClass)
Description copied from interface: MongoOperations
Returns a document with the given id mapped onto the given class. The collection the query is ran against will be derived from the given target class as well.

Specified by:
findById in interface MongoOperations
Parameters:
id - the id of the document to return.
entityClass - the type the document shall be converted into.
Returns:
the document with the given id mapped onto the given target class.

findById

public <T> T findById(Object id,
                      Class<T> entityClass,
                      String collectionName)
Description copied from interface: MongoOperations
Returns the document with the given id from the given collection mapped onto the given target class.

Specified by:
findById in interface MongoOperations
Parameters:
id - the id of the document to return
entityClass - the type to convert the document to
collectionName - the collection to query for the document
Returns:

geoNear

public <T> GeoResults<T> geoNear(NearQuery near,
                                 Class<T> entityClass)
Description copied from interface: MongoOperations
Returns GeoResult for all entities matching the given NearQuery. Will consider entity mapping information to determine the collection the query is ran against.

Specified by:
geoNear in interface MongoOperations
Parameters:
near - must not be null.
entityClass - must not be null.
Returns:

geoNear

public <T> GeoResults<T> geoNear(NearQuery near,
                                 Class<T> entityClass,
                                 String collectionName)
Description copied from interface: MongoOperations
Returns GeoResult for all entities matching the given NearQuery.

Specified by:
geoNear in interface MongoOperations
Parameters:
near - must not be null.
entityClass - must not be null.
collectionName - the collection to trigger the query against. If no collection name is given the entity class will be inspected.
Returns:

findAndModify

public <T> T findAndModify(Query query,
                           Update update,
                           Class<T> entityClass)
Specified by:
findAndModify in interface MongoOperations

findAndModify

public <T> T findAndModify(Query query,
                           Update update,
                           Class<T> entityClass,
                           String collectionName)
Specified by:
findAndModify in interface MongoOperations

findAndModify

public <T> T findAndModify(Query query,
                           Update update,
                           FindAndModifyOptions options,
                           Class<T> entityClass)
Specified by:
findAndModify in interface MongoOperations

findAndModify

public <T> T findAndModify(Query query,
                           Update update,
                           FindAndModifyOptions options,
                           Class<T> entityClass,
                           String collectionName)
Specified by:
findAndModify in interface MongoOperations

findAndRemove

public <T> T findAndRemove(Query query,
                           Class<T> entityClass)
Description copied from interface: MongoOperations
Map the results of an ad-hoc query on the collection for the entity type 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.

The object is converted from the MongoDB native representation using an instance of MongoConverter.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findAndRemove in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
Returns:
the converted object

findAndRemove

public <T> T findAndRemove(Query query,
                           Class<T> entityClass,
                           String collectionName)
Description copied from interface: MongoOperations
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.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query is specified as a Query which can be created either using the BasicQuery or the more feature rich Query.

Specified by:
findAndRemove in interface MongoOperations
Parameters:
query - the query class that specifies the criteria used to find a record and also an optional fields specification
entityClass - the parameterized type of the returned list.
collectionName - name of the collection to retrieve the objects from
Returns:
the converted object

count

public long count(Query query,
                  Class<?> entityClass)
Description copied from interface: MongoOperations
Returns the number of documents for the given Query by querying the collection of the given entity class.

Specified by:
count in interface MongoOperations
entityClass - must not be null.
Returns:

count

public long count(Query query,
                  String collectionName)
Description copied from interface: MongoOperations
Returns the number of documents for the given Query querying the given collection.

Specified by:
count in interface MongoOperations
collectionName - must not be null or empty.
Returns:

insert

public void insert(Object objectToSave)
Description copied from interface: MongoOperations
Insert the object into the collection for the entity type of the object to save.

The object is converted to the MongoDB native representation using an instance of MongoConverter.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. See Spring 3 Type Conversion" for more details.

Insert is used to initially store the object into the database. To update an existing object use the save method.

Specified by:
insert in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection.

insert

public void insert(Object objectToSave,
                   String collectionName)
Description copied from interface: MongoOperations
Insert the object into the specified collection.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

Insert is used to initially store the object into the database. To update an existing object use the save method.

Specified by:
insert in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection
collectionName - name of the collection to store the object in

ensureNotIterable

protected void ensureNotIterable(Object o)

prepareCollection

protected void prepareCollection(DBCollection collection)
Prepare the collection before any processing is done using it. This allows a convenient way to apply settings like slaveOk() etc. Can be overridden in sub-classes.

Parameters:
collection -

prepareWriteConcern

protected WriteConcern prepareWriteConcern(MongoAction mongoAction)
Prepare the WriteConcern before any processing is done using it. This allows a convenient way to apply custom settings in sub-classes.

Parameters:
writeConcern - any WriteConcern already configured or null
Returns:
The prepared WriteConcern or null

doInsert

protected <T> void doInsert(String collectionName,
                            T objectToSave,
                            MongoWriter<T> writer)

insert

public void insert(Collection<? extends Object> batchToSave,
                   Class<?> entityClass)
Description copied from interface: MongoOperations
Insert a Collection of objects into a collection in a single batch write to the database.

Specified by:
insert in interface MongoOperations
Parameters:
batchToSave - the list of objects to save.
entityClass - class that determines the collection to use

insert

public void insert(Collection<? extends Object> batchToSave,
                   String collectionName)
Description copied from interface: MongoOperations
Insert a list of objects into the specified collection in a single batch write to the database.

Specified by:
insert in interface MongoOperations
Parameters:
batchToSave - the list of objects to save.
collectionName - name of the collection to store the object in

insertAll

public void insertAll(Collection<? extends Object> objectsToSave)
Description copied from interface: MongoOperations
Insert a mixed Collection of objects into a database collection determining the collection name to use based on the class.

Specified by:
insertAll in interface MongoOperations

doInsertAll

protected <T> void doInsertAll(Collection<? extends T> listToSave,
                               MongoWriter<T> writer)

doInsertBatch

protected <T> void doInsertBatch(String collectionName,
                                 Collection<? extends T> batchToSave,
                                 MongoWriter<T> writer)

save

public void save(Object objectToSave)
Description copied from interface: MongoOperations
Save the object to the collection for the entity type of the object to save. This will perform an insert if the object is not already present, that is an 'upsert'.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. See Spring 3 Type Conversion" for more details.

Specified by:
save in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection

save

public void save(Object objectToSave,
                 String collectionName)
Description copied from interface: MongoOperations
Save the object to the specified collection. This will perform an insert if the object is not already present, that is an 'upsert'.

The object is converted to the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Cobnversion API. See Spring 3 Type Conversion" for more details.

Specified by:
save in interface MongoOperations
Parameters:
objectToSave - the object to store in the collection
collectionName - name of the collection to store the object in

doSave

protected <T> void doSave(String collectionName,
                          T objectToSave,
                          MongoWriter<T> writer)

insertDBObject

protected Object insertDBObject(String collectionName,
                                DBObject dbDoc,
                                Class<?> entityClass)

insertDBObjectList

protected List<ObjectId> insertDBObjectList(String collectionName,
                                            List<DBObject> dbDocList)

saveDBObject

protected Object saveDBObject(String collectionName,
                              DBObject dbDoc,
                              Class<?> entityClass)

upsert

public WriteResult upsert(Query query,
                          Update update,
                          Class<?> entityClass)
Description copied from interface: MongoOperations
Performs an upsert. If no document is found that matches the query, a new document is created and inserted by combining the query document and the update document.

Specified by:
upsert in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be upserted
update - the update document that contains the updated object or $ operators to manipulate the existing object
entityClass - class that determines the collection to use
Returns:
the WriteResult which lets you access the results of the previous write.

upsert

public WriteResult upsert(Query query,
                          Update update,
                          String collectionName)
Description copied from interface: MongoOperations
Performs an upsert. If no document is found that matches the query, a new document is created and inserted by combining the query document and the update document.

Specified by:
upsert in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be updated
update - the update document that contains the updated object or $ operators to manipulate the existing object.
collectionName - name of the collection to update the object in
Returns:
the WriteResult which lets you access the results of the previous write.

updateFirst

public WriteResult updateFirst(Query query,
                               Update update,
                               Class<?> entityClass)
Description copied from interface: MongoOperations
Updates the first object that is found in the collection of the entity class that matches the query document with the provided update document.

Specified by:
updateFirst in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be updated
update - the update document that contains the updated object or $ operators to manipulate the existing object.
entityClass - class that determines the collection to use
Returns:
the WriteResult which lets you access the results of the previous write.

updateFirst

public WriteResult updateFirst(Query query,
                               Update update,
                               String collectionName)
Description copied from interface: MongoOperations
Updates the first object that is found in the specified collection that matches the query document criteria with the provided updated document.

Specified by:
updateFirst in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be updated
update - the update document that contains the updated object or $ operators to manipulate the existing object.
collectionName - name of the collection to update the object in
Returns:
the WriteResult which lets you access the results of the previous write.

updateMulti

public WriteResult updateMulti(Query query,
                               Update update,
                               Class<?> entityClass)
Description copied from interface: MongoOperations
Updates all objects that are found in the collection for the entity class that matches the query document criteria with the provided updated document.

Specified by:
updateMulti in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be updated
update - the update document that contains the updated object or $ operators to manipulate the existing object.
entityClass - class that determines the collection to use
Returns:
the WriteResult which lets you access the results of the previous write.

updateMulti

public WriteResult updateMulti(Query query,
                               Update update,
                               String collectionName)
Description copied from interface: MongoOperations
Updates all objects that are found in the specified collection that matches the query document criteria with the provided updated document.

Specified by:
updateMulti in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to select a record to be updated
update - the update document that contains the updated object or $ operators to manipulate the existing object.
collectionName - name of the collection to update the object in
Returns:
the WriteResult which lets you access the results of the previous write.

doUpdate

protected WriteResult doUpdate(String collectionName,
                               Query query,
                               Update update,
                               Class<?> entityClass,
                               boolean upsert,
                               boolean multi)

remove

public void remove(Object object)
Description copied from interface: MongoOperations
Remove the given object from the collection by id.

Specified by:
remove in interface MongoOperations

remove

public void remove(Object object,
                   String collection)
Description copied from interface: MongoOperations
Removes the given object from the given collection.

Specified by:
remove in interface MongoOperations
collection - must not be null or empty.

remove

public <T> void remove(Query query,
                       Class<T> entityClass)
Description copied from interface: MongoOperations
Remove all documents that match the provided query document criteria from the the collection used to store the entityClass. The Class parameter is also used to help convert the Id of the object if it is present in the query.

Specified by:
remove in interface MongoOperations

doRemove

protected <T> void doRemove(String collectionName,
                            Query query,
                            Class<T> entityClass)

remove

public void remove(Query query,
                   String collectionName)
Description copied from interface: MongoOperations
Remove all documents from the specified collection that match the provided query document criteria. There is no conversion/mapping done for any criteria using the id field.

Specified by:
remove in interface MongoOperations
Parameters:
query - the query document that specifies the criteria used to remove a record
collectionName - name of the collection where the objects will removed

findAll

public <T> List<T> findAll(Class<T> entityClass)
Description copied from interface: MongoOperations
Query for a list of objects of type T from the collection used by the entity class.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way to map objects since the test for class type is done in the client and not on the server.

Specified by:
findAll in interface MongoOperations
Parameters:
entityClass - the parameterized type of the returned list
Returns:
the converted collection

findAll

public <T> List<T> findAll(Class<T> entityClass,
                           String collectionName)
Description copied from interface: MongoOperations
Query for a list of objects of type T from the specified collection.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way to map objects since the test for class type is done in the client and not on the server.

Specified by:
findAll in interface MongoOperations
Parameters:
entityClass - the parameterized type of the returned list.
collectionName - name of the collection to retrieve the objects from
Returns:
the converted collection

mapReduce

public <T> MapReduceResults<T> mapReduce(String inputCollectionName,
                                         String mapFunction,
                                         String reduceFunction,
                                         Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a map-reduce operation. The map-reduce operation will be formed with an output type of INLINE

Specified by:
mapReduce in interface MongoOperations
Parameters:
inputCollectionName - the collection where the map-reduce will read from
mapFunction - The JavaScript map function
reduceFunction - The JavaScript reduce function
entityClass - The parameterized type of the returned list
Returns:
The results of the map reduce operation

mapReduce

public <T> MapReduceResults<T> mapReduce(String inputCollectionName,
                                         String mapFunction,
                                         String reduceFunction,
                                         MapReduceOptions mapReduceOptions,
                                         Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a map-reduce operation that takes additional map-reduce options.

Specified by:
mapReduce in interface MongoOperations
Parameters:
inputCollectionName - the collection where the map-reduce will read from
mapFunction - The JavaScript map function
reduceFunction - The JavaScript reduce function
mapReduceOptions - Options that specify detailed map-reduce behavior
entityClass - The parameterized type of the returned list
Returns:
The results of the map reduce operation

mapReduce

public <T> MapReduceResults<T> mapReduce(Query query,
                                         String inputCollectionName,
                                         String mapFunction,
                                         String reduceFunction,
                                         Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a map-reduce operation that takes a query. The map-reduce operation will be formed with an output type of INLINE

Specified by:
mapReduce in interface MongoOperations
Parameters:
query - The query to use to select the data for the map phase
inputCollectionName - the collection where the map-reduce will read from
mapFunction - The JavaScript map function
reduceFunction - The JavaScript reduce function
entityClass - The parameterized type of the returned list
Returns:
The results of the map reduce operation

mapReduce

public <T> MapReduceResults<T> mapReduce(Query query,
                                         String inputCollectionName,
                                         String mapFunction,
                                         String reduceFunction,
                                         MapReduceOptions mapReduceOptions,
                                         Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a map-reduce operation that takes a query and additional map-reduce options

Specified by:
mapReduce in interface MongoOperations
Parameters:
query - The query to use to select the data for the map phase
inputCollectionName - the collection where the map-reduce will read from
mapFunction - The JavaScript map function
reduceFunction - The JavaScript reduce function
mapReduceOptions - Options that specify detailed map-reduce behavior
entityClass - The parameterized type of the returned list
Returns:
The results of the map reduce operation

group

public <T> GroupByResults<T> group(String inputCollectionName,
                                   GroupBy groupBy,
                                   Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a group operation over the entire collection. The group operation entity class should match the 'shape' of the returned object that takes int account the initial document structure as well as any finalize functions.

Specified by:
group in interface MongoOperations
Parameters:
inputCollectionName - the collection where the group operation will read from
groupBy - the conditions under which the group operation will be performed, e.g. keys, initial document, reduce function.
entityClass - The parameterized type of the returned list
Returns:
The results of the group operation

group

public <T> GroupByResults<T> group(Criteria criteria,
                                   String inputCollectionName,
                                   GroupBy groupBy,
                                   Class<T> entityClass)
Description copied from interface: MongoOperations
Execute a group operation restricting the rows to those which match the provided Criteria. The group operation entity class should match the 'shape' of the returned object that takes int account the initial document structure as well as any finalize functions.

Specified by:
group in interface MongoOperations
Parameters:
criteria - The criteria that restricts the row that are considered for grouping. If not specified all rows are considered.
inputCollectionName - the collection where the group operation will read from
groupBy - the conditions under which the group operation will be performed, e.g. keys, initial document, reduce function.
entityClass - The parameterized type of the returned list
Returns:
The results of the group operation

replaceWithResourceIfNecessary

protected String replaceWithResourceIfNecessary(String function)

getCollectionNames

public Set<String> getCollectionNames()
Description copied from interface: MongoOperations
A set of collection names.

Specified by:
getCollectionNames in interface MongoOperations
Returns:
list of collection names

getDb

public DB getDb()

maybeEmitEvent

protected <T> void maybeEmitEvent(MongoMappingEvent<T> event)

doCreateCollection

protected DBCollection doCreateCollection(String collectionName,
                                          DBObject collectionOptions)
Create the specified collection using the provided options

Parameters:
collectionName -
collectionOptions -
Returns:
the collection that was created

doFindOne

protected <T> T doFindOne(String collectionName,
                          DBObject query,
                          DBObject fields,
                          Class<T> entityClass)
Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
entityClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

doFind

protected <T> List<T> doFind(String collectionName,
                             DBObject query,
                             DBObject fields,
                             Class<T> entityClass,
                             org.springframework.data.mongodb.core.CursorPreparer preparer)
Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.

The object is converted from the MongoDB native representation using an instance of MongoConverter. Unless configured otherwise, an instance of SimpleMongoConverter will be used.

The query document is specified as a standard DBObject and so is the fields specification.

Can be overridden by subclasses.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
entityClass - the parameterized type of the returned list.
preparer - allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and so on).
Returns:
the List of converted objects.

doFind

protected <S,T> List<T> doFind(String collectionName,
                               DBObject query,
                               DBObject fields,
                               Class<S> entityClass,
                               org.springframework.data.mongodb.core.CursorPreparer preparer,
                               org.springframework.data.mongodb.core.MongoTemplate.DbObjectCallback<T> objectCallback)

doFind

protected <T> List<T> doFind(String collectionName,
                             DBObject query,
                             DBObject fields,
                             Class<T> entityClass)
Map the results of an ad-hoc query on the default MongoDB collection to a List using the template's converter.

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
fields - the document that specifies the fields to be returned
entityClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

convertToDbObject

protected DBObject convertToDbObject(CollectionOptions collectionOptions)

doFindAndRemove

protected <T> T doFindAndRemove(String collectionName,
                                DBObject query,
                                DBObject fields,
                                DBObject sort,
                                Class<T> entityClass)
Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter. The first document that matches the query is returned and also removed from the collection in the database.

The query document is specified as a standard DBObject and so is the fields specification.

Parameters:
collectionName - name of the collection to retrieve the objects from
query - the query document that specifies the criteria used to find a record
entityClass - the parameterized type of the returned list.
Returns:
the List of converted objects.

doFindAndModify

protected <T> T doFindAndModify(String collectionName,
                                DBObject query,
                                DBObject fields,
                                DBObject sort,
                                Class<T> entityClass,
                                Update update,
                                FindAndModifyOptions options)

populateIdIfNecessary

protected void populateIdIfNecessary(Object savedObject,
                                     Object id)
Populates the id property of the saved object, if it's not set already.

Parameters:
savedObject -
id -

handleAnyWriteResultErrors

protected void handleAnyWriteResultErrors(WriteResult wr,
                                          DBObject query,
                                          String operation)
Checks and handles any errors.

Current implementation logs errors. Future version may make this configurable to log warning, errors or throw exception.


Spring Data Document

Copyright © 2012. All Rights Reserved.