mongodb和spring集成中MongoTemplate的总结是使用方法
基础实体类
@Document(collection="person")
class Person{
String id;
String name;
int age;
public String getId() {
returnid;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
returnname;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
returnage;
}
public void setAge(int age) {
this.age = age;
}
}
/**
* The collection name used for the specifiedclass by this template.
*
* @param entityClass must not be {@literalnull}.
* @return
*/
StringgetCollectionName(Class<?> entityClass);
String personName=mongoTemplate.getCollectionName(Person.class);
/**
* Execute the a MongoDB command expressed as aJSON string. This will call the method JSON.parse that is part of the
* MongoDB driver to convert the JSON string toa DBObject. Any errors that result from executing this command will be
* converted into Spring's DAO exceptionhierarchy.
*
* @param jsonCommand a MongoDB commandexpressed as a JSON string.
*/
CommandResultexecuteCommand(String jsonCommand);
String jsonSql="{distinct:'person', key:'name'}";
CommandResult commandResult=mongoTemplate.executeCommand(jsonSql);
System.out.println();
BasicDBList list = (BasicDBList)commandResult.get("values");
for (int i = 0; i < list.size(); i ++) {
System.out.println(list.get(i));
}
System.out.println();
/**
* Execute a MongoDB command. Any errors thatresult from executing this command will be converted into Spring's DAO
* exception hierarchy.
*
* @param command a MongoDB command
*/
CommandResultexecuteCommand(DBObject command);
String jsonSql="{distinct:'person', key:'name'}";
CommandResult commandResult=mongoTemplate.executeCommand((DBObject) JSON.parse(jsonSql));
System.out.println();
BasicDBList list = (BasicDBList)commandResult.get("values");
for (int i = 0; i < list.size(); i ++) {
System.out.println(list.get(i));
}
System.out.println();
/**
* Execute a MongoDB command. Any errors thatresult from executing this command will be converted into Spring's DAO
* exception hierarchy.
*
* @param command a MongoDB command
* @param options query options to use
*/
CommandResultexecuteCommand(DBObject command, int options);
String jsonSql="{distinct:'person', key:'name'}";
CommandResult commandResult=mongoTemplate.executeCommand((DBObject) JSON.parse(jsonSql),Bytes.QUERYOPTION_NOTIMEOUT);
System.out.println();
BasicDBList list = (BasicDBList)commandResult.get("values");
for (int i = 0; i < list.size(); i ++) {
System.out.println(list.get(i));
}
System.out.println();
/**
* Execute a MongoDB query and iterate over thequery results on a per-document basis with a DocumentCallbackHandler.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param collectionName name of the collectionto retrieve the objects from
* @param dch the handler that will extractresults, one document at a time
*/
void executeQuery(Queryquery, String collectionName, DocumentCallbackHandler dch);
final Query query =new Query();
Criteria criteria =new Criteria();
criteria.and("name").is("zhangsan");
mongoTemplate.executeQuery(query,"person",new DocumentCallbackHandler() {
//处理自己的逻辑,这种为了有特殊需要功能的留的开放接口命令模式
public void processDocument(DBObject dbObject) throws MongoException,
DataAccessException {
mongoTemplate.updateFirst(query, Update.update("name","houchangren"),"person");
}
});
/**
* Executes a {@link DbCallback} translatingany exceptions as necessary.
* <p/>
* Allows for returning a result object, thatis a domain object or a collection of domain objects.
*
* @param <T> return type
* @param action callback object that specifiesthe MongoDB actions to perform on the passed in DB instance.
* @return a result object returned by theaction or <tt>null</tt>
*/
<T> Texecute(DbCallback<T> action);
Person person=mongoTemplate.execute(new DbCallback<Person>() {
public Person doInDB(DB db)throws MongoException, DataAccessException {
Person p=new Person();
//自己写逻辑和查询处理
// p.setAge(age);
return p;
}
});
/**
* Executes the given {@linkCollectionCallback} on the entity collection of the specified class.
* <p/>
* Allows for returning a result object, thatis a domain object or a collection of domain objects.
*
* @param entityClass class that determines thecollection to use
* @param <T> return type
* @param action callback object that specifiesthe MongoDB action
* @return a result object returned by theaction or <tt>null</tt>
*/
<T> Texecute(Class<?> entityClass, CollectionCallback<T> action);
Person person=mongoTemplate.execute(Person.class,new CollectionCallback<Person>() {
public Person doInCollection(DBCollection collection)
throws MongoException, DataAccessException {
Person p=new Person();
//自己取值然后处理返回对应的处理 collection.find();
return p;
}
});
/**
* Executes the given {@linkCollectionCallback} on the collection of the given name.
* <p/>
* Allows for returning a result object, thatis a domain object or a collection of domain objects.
*
* @param <T> return type
* @param collectionName the name of thecollection that specifies which DBCollection instance will be passed into
* @param action callback object that specifiesthe MongoDB action the callback action.
* @return a result object returned by theaction or <tt>null</tt>
*/
<T> Texecute(String collectionName, CollectionCallback<T> action);
Person person=mongoTemplate.execute(“person”,new CollectionCallback<Person>() {
public Person doInCollection(DBCollection collection)
throws MongoException, DataAccessException {
Person p=new Person();
//自己取值然后处理返回对应的处理 collection.find();
return p;
}
});
/**
* Executes the given {@link DbCallback} withinthe same connection to the database so as to ensure consistency in a
* write heavy environment where you may readthe data that you wrote. See the comments on {@see <a
*href=http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency>Java DriverConcurrency</a>}
* <p/>
* Allows for returning a result object, thatis a domain object or a collection of domain objects.
*
* @param <T> return type
* @param action callback that specified theMongoDB actions to perform on the DB instance
* @return a result object returned by theaction or <tt>null</tt>
*/
<T> T executeInSession(DbCallback<T>action);
Person person=mongoTemplate.executeInSession(new DbCallback<Person>() {
public Person doInDB(DB db)throws MongoException, DataAccessException {
//处理..
return null;
}
});
/**
* Create an uncapped collection with a namebased on the provided entity class.
*
* @param entityClass class that determines thecollection to create
* @return the created collection
*/
<T>DBCollection createCollection(Class<T> entityClass);
/**
* Create a collect with a name based on theprovided entity class using the options.
*
* @param entityClass class that determines thecollection to create
* @param collectionOptions options to use whencreating the collection.
* @return the created collection
*/
<T>DBCollection createCollection(Class<T> entityClass, CollectionOptionscollectionOptions);
创建高级特性集合(指定大小,层级等属性)
/**
* Create an uncapped collection with theprovided name.
*
* @param collectionName name of the collection
* @return the created collection
*/
DBCollectioncreateCollection(String collectionName);
/**
* Create a collect with the provided name andoptions.
*
* @param collectionName name of the collection
* @param collectionOptions options to use whencreating the collection.
* @return the created collection
*/
DBCollectioncreateCollection(String collectionName, CollectionOptions collectionOptions);
/**
* A set of collection names.
*
* @return list of collection names
*/
Set<String>getCollectionNames();
Set<String> collectionNames=mongoTemplate.getCollectionNames();
/**
* Get a collection by name, creating it if itdoesn't exist.
* <p/>
* Translate any exceptions as necessary.
*
* @param collectionName name of the collection
* @return an existing collection or a newlycreated one.
*/
DBCollectiongetCollection(String collectionName);
DBCollection collection=mongoTemplate.getCollection("person");
/**
* Check to see if a collection with a nameindicated by the entity class exists.
* <p/>
* Translate any exceptions as necessary.
*
* @param entityClass class that determines thename of the collection
* @return true if a collection with the givenname is found, false otherwise.
*/
<T>boolean collectionExists(Class<T> entityClass);
省略…
/**
* Check to see if a collection with a givenname exists.
* <p/>
* Translate any exceptions as necessary.
*
* @param collectionName name of the collection
* @return true if a collection with the givenname is found, false otherwise.
*/
booleancollectionExists(String collectionName);
省略…
/**
* Drop the collection with the name indicatedby the entity class.
* <p/>
* Translate any exceptions as necessary.
*
* @param entityClass class that determines thecollection to drop/delete.
*/
<T> voiddropCollection(Class<T> entityClass);
删除集合
/**
* Drop the collection with the given name.
* <p/>
* Translate any exceptions as necessary.
*
* @param collectionName name of the collectionto drop/delete.
*/
voiddropCollection(String collectionName);
省略…
/**
* Returns the operations that can be performedon indexes
*
* @return index operations on the namedcollection
*/
IndexOperationsindexOps(String collectionName);
IndexOperations io=mongoTemplate.indexOps("person");
//io.dropIndex("");
Index index =new Index();
index.on("name",Order.ASCENDING); //为name属性加上 索引
index.unique();//唯一索引
io.ensureIndex(index);
/**
* Returns the operations that can be performedon indexes
*
* @return index operations on the namedcollection associated with the given entity class
*/
IndexOperationsindexOps(Class<?> entityClass);
IndexOperations io=mongoTemplate.indexOps(Person.class);
io.dropIndex("name_1");//删除索引
// Index index =new Index();
// index.on("name",Order.ASCENDING);
// index.unique();
// index.named("name_1");
// io.ensureIndex(index);
/**
* Query for a list of objects of type T fromthe collection used by the entity class.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance of SimpleMongoConverterwill be used.
* <p/>
* If your collection does not contain ahomogeneous collection of types, this operation will not be an efficient way
* to map objects since the test for class typeis done in the client and not on the server.
*
* @param entityClass the parameterized type ofthe returned list
* @return the converted collection
*/
<T>List<T> findAll(Class<T> entityClass);
mongoTemplate.findAll(Person.class);
mongoTemplate.findAll(Person.class,"person");
/**
* Query for a list of objects of type T fromthe specified collection.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* If your collection does not contain ahomogeneous collection of types, this operation will not be an efficient way
* to map objects since the test for class typeis done in the client and not on the server.
*
* @param entityClass the parameterized type ofthe returned list.
* @param collectionName name of the collectionto retrieve the objects from
* @return the converted collection
*/
<T>List<T> findAll(Class<T> entityClass, String collectionName);
mongoTemplate.findAll(Person.class);
mongoTemplate.findAll(Person.class,"person");
/**
* Execute a group operation over the entirecollection. The group operation entity class should match the 'shape' of
* the returned object that takes int accountthe initial document structure as well as any finalize functions.
*
* @param criteria The criteria that restrictsthe row that are considered for grouping. If not specified all rows are
* considered.
* @param inputCollectionName the collectionwhere the group operation will read from
* @param groupBy the conditions under whichthe group operation will be performed, e.g. keys, initial document,
* reduce function.
* @param entityClass The parameterized type ofthe returned list
* @return The results of the group operation
*/
<T> GroupByResults<T>group(String inputCollectionName, GroupBy groupBy, Class<T> entityClass);
//处理所有相同名字的人有几个?
GroupBy groupBy = GroupBy.key("name").initialDocument("{allAgeTotal:0,count:0}")
.reduceFunction("function(key, values){values.count+=1;}");
//values.allAgeTotal+=values.age;
//.reduceFunction("function(key, values){var x=0;values.forEach(function(v){x+=v;});return x;}");
GroupByResults<Person> r = mongoTemplate.group("person", groupBy, Person.class);
BasicDBList list = (BasicDBList)r.getRawResults().get("retval");
for (int i = 0; i < list.size(); i ++) {
BasicDBObject obj = (BasicDBObject)list.get(i);
System.out.println("[LOG]姓名:"+obj.get("name")+"数量:"+obj.get("count"));
}
System.out.println(r);
结果:
[LOG]姓名:houchangren数量:1.0
[LOG]姓名:zhangsan数量:8.0
//查询年龄总和是多少,和数量是是多少?
GroupBy groupBy = GroupBy.key("age").initialDocument("{allAgeTotal:0,count:0,avg:0}")
.reduceFunction("function(doc, prev){if(prev.age>=16){prev.allAgeTotal+=prev.age;prev.count+=1;}}");
// .finalizeFunction("function(prev){prev.avg=prev.allAgeTotal/prev.count;}");
GroupByResults<Person> r = mongoTemplate.group("person", groupBy, Person.class);
BasicDBList list = (BasicDBList)r.getRawResults().get("retval");
for (int i = 0; i < list.size(); i ++) {
BasicDBObject obj = (BasicDBObject)list.get(i);
System.out.println("[LOG]年龄为:"+obj.get("age")+",数量:"+obj.get("count")+"年龄总和:"+obj.get("allAgeTotal"));
}
//
[LOG]年龄为:16.0,数量:1.0年龄总和:16.0
[LOG]年龄为:15.0,数量:0.0年龄总和:0.0
[LOG]年龄为:25.0,数量:6.0年龄总和:150.0
/**
* Execute a group operation restricting therows to those which match the provided Criteria. The group operation
* entity class should match the 'shape' of thereturned object that takes int account the initial document structure
* as well as any finalize functions.
*
* @param criteria The criteria that restrictsthe row that are considered for grouping. If not specified all rows are
* considered.
* @param inputCollectionName the collectionwhere the group operation will read from
* @param groupBy the conditions under whichthe group operation will be performed, e.g. keys, initial document,
* reduce function.
* @param entityClass The parameterized type ofthe returned list
* @return The results of the group operation
*/
<T>GroupByResults<T> group(Criteria criteria, String inputCollectionName,GroupBy groupBy, Class<T> entityClass);
// //大于16以上的查询年龄总和是多少,和数量是是多少?
GroupBy groupBy = GroupBy.key("age").initialDocument("{allAgeTotal:0,count:0,avg:0}")
.reduceFunction("function(doc, prev){if(prev.age>=16){prev.allAgeTotal+=prev.age;prev.count+=1;}}");
// .finalizeFunction("function(prev){prev.avg=prev.allAgeTotal/prev.count;}");
Criteria criteria =new Criteria();
criteria.and("age").gt(16);
GroupByResults<Person> r = mongoTemplate.group(criteria,"person", groupBy, Person.class);
BasicDBList list = (BasicDBList)r.getRawResults().get("retval");
for (int i = 0; i < list.size(); i ++) {
BasicDBObject obj = (BasicDBObject)list.get(i);
System.out.println("[LOG]年龄为:"+obj.get("age")+",数量:"+obj.get("count")+"年龄总和:"+obj.get("allAgeTotal"));
}
/**
* Execute a map-reduce operation. Themap-reduce operation will be formed with an output type of INLINE
*
* @param inputCollectionName the collectionwhere the map-reduce will read from
* @param mapFunction The JavaScript mapfunction
* @param reduceFunction The JavaScript reducefunction
* @param mapReduceOptions Options that specifydetailed map-reduce behavior
* @param entityClass The parameterized type ofthe returned list
* @return The results of the map reduceoperation
*/
<T>MapReduceResults<T> mapReduce(String inputCollectionName, StringmapFunction, String reduceFunction, Class<T>entityClass);
String mapFunction="function(){" +
"emit(this.age,{'name':this.name});" +
"}";
String reduceFunction="function(key, values)" +
"{var sum = 0;" +
"var test='';" +
"for(i in values){" +
"test+=i;" +
"}" +
"" +
"values.forEach(function(doc){" +
"sum += 1; }); " +
"return {persons:sum,test:test,values:values};" +
"};";
//在此之前用的sping -data-mongodb 1.0.1.release版本,存在BUG,现在1.1.0.release没有问题
// Criteria criteria =new Criteria();
// criteria.and("age").gt(16);
// Query query =new Query(criteria);
MapReduceResults<Person> mapReduce = mongoTemplate.mapReduce("person", mapFunction, reduceFunction, Person.class);
BasicDBList list = (BasicDBList)mapReduce.getRawResults().get("results");
for (int i = 0; i < list.size(); i ++) {
BasicDBObject obj = (BasicDBObject)list.get(i);
System.out.println(obj.toString());
}
/**
* Execute a map-reduce operation that takesadditional map-reduce options.
*
* @param inputCollectionName the collectionwhere the map-reduce will read from
* @param mapFunction The JavaScript mapfunction
* @param reduceFunction The JavaScript reducefunction
* @param mapReduceOptions Options that specifydetailed map-reduce behavior
* @param entityClass The parameterized type ofthe returned list
* @return The results of the map reduceoperation
*/
<T>MapReduceResults<T> mapReduce(String inputCollectionName, StringmapFunction, String reduceFunction, MapReduceOptionsmapReduceOptions, Class<T> entityClass);
String mapFunction = "function(){"
+ "emit(this.age,{'name':this.name});" +"}";
String reduceFunction = "function(key, values)" +"{var sum = 0;"
+ "var test='';" +"for(i in values){" +"test+=i;" +"}" +""
+ "values.forEach(function(doc){" +"sum += 1; }); "
+ "return {persons:sum,test:test,values:values};" +"};";
// 在此之前用的sping -data-mongodb 1.0.1.release版本,存在BUG,现在1.1.0.release没有问题
Criteria criteria =new Criteria();
criteria.and("age").gt(16);
Query query =new Query(criteria);
MapReduceOptions mrO=new MapReduceOptions();
mrO.outputCollection("person_result");//指定到输出表中,不指定输出的选项会把执行结果返回到result中
MapReduceResults<Person> mapReduce = mongoTemplate.mapReduce("person",
mapFunction, reduceFunction,mrO,Person.class);
// BasicDBList list = (BasicDBList) mapReduce.getRawResults().get(
// "results");
// for (int i = 0; i < list.size(); i++) {
// BasicDBObject obj = (BasicDBObject) list.get(i);
// System.out.println(obj.toString());
// }
System.out.println("+++++++++++++++++++++++++++++++");
//然后到输出的结果表中去查询
List<DBObject> person_results = mongoTemplate.execute("person_result",new CollectionCallback<List<DBObject> >() {
public List<DBObject> doInCollection(DBCollection collection)
throws MongoException, DataAccessException {
DBCursor dbCursor=collection.find();
return dbCursor.toArray();
}
});
for (DBObject dbObject : person_results) {
System.out.println(dbObject.toString());
}
/**
* Execute a map-reduce operation that takes aquery. The map-reduce operation will be formed with an output type of
* INLINE
*
* @param query The query to use to select thedata for the map phase
* @param inputCollectionName the collectionwhere the map-reduce will read from
* @param mapFunction The JavaScript mapfunction
* @param reduceFunction The JavaScript reducefunction
* @param mapReduceOptions Options that specifydetailed map-reduce behavior
* @param entityClass The parameterized type ofthe returned list
* @return The results of the map reduceoperation
*/
<T>MapReduceResults<T> mapReduce(Query query, String inputCollectionName,String mapFunction, String reduceFunction,
Class<T>entityClass);
/**
* Execute a map-reduce operation that takes aquery and additional map-reduce options
*
* @param query The query to use to select thedata for the map phase
* @param inputCollectionName the collectionwhere the map-reduce will read from
* @param mapFunction The JavaScript mapfunction
* @param reduceFunction The JavaScript reducefunction
* @param mapReduceOptions Options that specifydetailed map-reduce behavior
* @param entityClass The parameterized type ofthe returned list
* @return The results of the map reduceoperation
*/
<T>MapReduceResults<T> mapReduce(Query query, String inputCollectionName,String mapFunction, String reduceFunction,MapReduceOptions mapReduceOptions,Class<T> entityClass);
同上,不过就是加了一个普通的query 作为查询条件之前的过滤
/**
* Returns {@link GeoResult} for all entitiesmatching the given {@link NearQuery}. Will consider entity mapping
* information to determine the collection thequery is ran against.
*
* @param near must not be {@literal null}.
* @param entityClass must not be {@literalnull}.
* @return
*/
<T>GeoResults<T> geoNear(NearQuery near, Class<T> entityClass);
/**
* Returns {@link GeoResult} for all entitiesmatching the given {@link NearQuery}.
*
* @param near must not be {@literal null}.
* @param entityClass must not be {@literalnull}.
* @param collectionName the collection totrigger the query against. If no collection name is given the entity class
* will be inspected.
* @return
*/
<T>GeoResults<T> geoNear(NearQuery near, Class<T> entityClass, StringcollectionName);
// IndexOperations io=mongoTemplate.indexOps("person");
// //io.dropIndex("");
// GeospatialIndex index =new GeospatialIndex("address");
//// index.named("address_2d");
// index.withBits(26);
// index.withMax(900);
// index.withMin(0);
// io.ensureIndex(index);
double x =12,y=32;
Point point =new Point(x, y);
NearQuery near =NearQuery.near(point);
// Query query =new Query();
// query.limit(20);
// near.query(query);
near.maxDistance(10);
GeoResults<Person> geoResults = mongoTemplate.geoNear(near, Person.class);
for (GeoResult<Person> geoResult : geoResults) {
System.out.println(geoResult.getContent().toString());
}
/**
* Map the results of an ad-hoc query on thecollection for the entity class to a single instance of an object of the
* specified type.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @return the converted object
*/
<T> TfindOne(Query query, Class<T> entityClass);
/**
* Map the results of an ad-hoc query on thespecified collection to a single instance of an object of the specified
* type.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @param collectionName name of the collectionto retrieve the objects from
*
* @return the converted object
*/
<T> T findOne(Queryquery, Class<T> entityClass, String collectionName);
/**
* Map the results of an ad-hoc query on thecollection for the entity class to a List of the specified type.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @return the List of converted objects
*/
<T>List<T> find(Query query, Class<T> entityClass);
/**
* Map the results of an ad-hoc query on thespecified collection to a List of the specified type.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @param collectionName name of the collectionto retrieve the objects from
*
* @return the List of converted objects
*/
<T>List<T> find(Query query, Class<T> entityClass, StringcollectionName);
/**
* Returns a document with the given id mappedonto the given class. The collection the query is ran against will be
* derived from the given target class as well.
*
* @param <T>
* @param id the id of the document to return.
* @param entityClass the type the documentshall be converted into.
* @return the document with the given idmapped onto the given target class.
*/
<T> TfindById(Object id, Class<T> entityClass);
/**
* Returns the document with the given id fromthe given collection mapped onto the given target class.
*
* @param id the id of the document to return
* @param entityClass the type to convert thedocument to
* @param collectionName the collection toquery for the document
*
* @param <T>
* @return
*/
<T> TfindById(Object id, Class<T> entityClass, String collectionName);
<T> TfindAndModify(Query query, Update update, Class<T> entityClass);
<T> TfindAndModify(Query query, Update update, Class<T> entityClass, StringcollectionName);
<T> TfindAndModify(Query query, Update update, FindAndModifyOptions options,Class<T> entityClass);
<T> TfindAndModify(Query query, Update update, FindAndModifyOptions options,Class<T> entityClass, StringcollectionName);
/**
* Map the results of an ad-hoc query on thecollection for the entity type to a single instance of an object of the
* specified type. The first document thatmatches the query is returned and also removed from the collection in the
* database.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @return the converted object
*/
<T> TfindAndRemove(Query query, Class<T> entityClass);
/**
* Map the results of an ad-hoc query on thespecified collection to a single instance of an object of the specified
* type. The first document that matches thequery is returned and also removed from the collection in the database.
* <p/>
* The object is converted from the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* The query is specified as a {@link Query}which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}.
*
* @param query the query class that specifiesthe criteria used to find a record and also an optional fields
* specification
* @param entityClass the parameterized type ofthe returned list.
* @param collectionName name of the collectionto retrieve the objects from
*
* @return the converted object
*/
<T> TfindAndRemove(Query query, Class<T> entityClass, String collectionName);
/**
* Returns the number of documents for thegiven {@link Query} by querying the collection of the given entity class.
*
* @param query
* @param entityClass must not be {@literalnull}.
* @return
*/
longcount(Query query, Class<?> entityClass);
/**
* Returns the number of documents for thegiven {@link Query} querying the given collection.
*
* @param query
* @param collectionName must not be {@literalnull} or empty.
* @return
*/
longcount(Query query, String collectionName);
/**
* Insert the object into the collection forthe entity type of the object to save.
* <p/>
* The object is converted to the MongoDBnative representation using an instance of {@see MongoConverter}.
* <p/>
* If you object has an "Id' property, itwill be set with the generated Id from MongoDB. If your Id property is a
* String then MongoDB ObjectId will be used topopulate that string. Otherwise, the conversion from ObjectId to your
* property type will be handled by Spring'sBeanWrapper class that leverages Spring 3.0's new Type Conversion API.
* See <ahref="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html#core-convert">Spring3 Type
* Conversion"</a> for more details.
* <p/>
* <p/>
* Insert is used to initially store the objectinto the database. To update an existing object use the save method.
*
* @param objectToSave the object to store inthe collection.
*/
voidinsert(Object objectToSave);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
mongoTemplate.insert(person);
/**
* Insert the object into the specifiedcollection.
* <p/>
* The object is converted to the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* Insert is used to initially store the objectinto the database. To update an existing object use the save method.
*
* @param objectToSave the object to store inthe collection
* @param collectionName name of the collectionto store the object in
*/
voidinsert(Object objectToSave, String collectionName);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
mongoTemplate.insert(person, "person");
/**
* Insert a Collection of objects into acollection in a single batch write to the database.
*
* @param batchToSave the list of objects tosave.
* @param entityClass class that determines thecollection to use
*/
voidinsert(Collection<? extends Object> batchToSave, Class<?>entityClass);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
Person person2 =new Person();
person2.setAge(16);
person2.setName("lisi");
List<Person> persons=new ArrayList<Person>();
persons.add(person);
persons.add(person2);
mongoTemplate.insert(persons,Person.class);
/**
* Insert a list of objects into the specifiedcollection in a single batch write to the database.
*
* @param batchToSave the list of objects tosave.
* @param collectionName name of the collectionto store the object in
*/
voidinsert(Collection<? extends Object> batchToSave, String collectionName);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
Person person2 =new Person();
person2.setAge(16);
person2.setName("lisi");
List<Person> persons=new ArrayList<Person>();
persons.add(person);
persons.add(person2);
mongoTemplate.insert(persons, "person");
/**
* Insert a mixed Collection of objects into adatabase collection determining the collection name to use based on the
* class.
*
* @param collectionToSave the list of objectsto save.
*/
voidinsertAll(Collection<? extends Object> objectsToSave);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
Person person2 =new Person();
person2.setAge(16);
person2.setName("lisi");
List<Person> persons=new ArrayList<Person>();
persons.add(person);
persons.add(person2);
mongoTemplate.insertAll(persons);
/**
* Save the object to the collection for theentity type of the object to save. This will perform an insert if the
* object is not already present, that is an'upsert'.
* <p/>
* The object is converted to the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* If you object has an "Id' property, itwill be set with the generated Id from MongoDB. If your Id property is a
* String then MongoDB ObjectId will be used topopulate that string. Otherwise, the conversion from ObjectId to your
* property type will be handled by Spring'sBeanWrapper class that leverages Spring 3.0's new Type Conversion API.
* See <ahref="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html#core-convert">Spring3 Type
* Conversion"</a> for more details.
*
* @param objectToSave the object to store inthe collection
*/
voidsave(Object objectToSave);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
mongoTemplate.save(person);
/**
* Save the object to the specified collection.This will perform an insert if the object is not already present, that
* is an 'upsert'.
* <p/>
* The object is converted to the MongoDBnative representation using an instance of {@see MongoConverter}. Unless
* configured otherwise, an instance ofSimpleMongoConverter will be used.
* <p/>
* If you object has an "Id' property, itwill be set with the generated Id from MongoDB. If your Id property is a
* String then MongoDB ObjectId will be used topopulate that string. Otherwise, the conversion from ObjectId to your
* property type will be handled by Spring'sBeanWrapper class that leverages Spring 3.0's new Type Cobnversion API.
* See <ahref="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html#core-convert">Spring3 Type
* Conversion"</a> for more details.
*
* @param objectToSave the object to store inthe collection
* @param collectionName name of the collectionto store the object in
*/
voidsave(Object objectToSave, String collectionName);
Person person =new Person();
person.setAge(15);
person.setName("zhangsan");
mongoTemplate.save(person,"person");
/**
* Performs an upsert. If no document is foundthat matches the query, a new document is created and inserted by
* combining the query document and the updatedocument.
*
* @param query the query document thatspecifies the criteria used to select a record to be upserted
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing object
* @param entityClass class that determines thecollection to use
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupsert(Query query, Update update, Class<?> entityClass);
/**
* Performs an upsert. If no document is foundthat matches the query, a new document is created and inserted by
* combining the query document and the updatedocument.
*
* @param query the query document thatspecifies the criteria used to select a record to be updated
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing
* object.
* @param collectionName name of the collectionto update the object in
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupsert(Query query, Update update, String collectionName);
/**
* Updates the first object that is found inthe collection of the entity class that matches the query document with
* the provided update document.
*
* @param query the query document thatspecifies the criteria used to select a record to be updated
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing
* object.
* @param entityClass class that determines thecollection to use
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupdateFirst(Query query, Update update, Class<?> entityClass);
/**
* Updates the first object that is found inthe specified collection that matches the query document criteria with
* the provided updated document.
*
* @param query the query document thatspecifies the criteria used to select a record to be updated
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing
* object.
* @param collectionName name of the collectionto update the object in
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupdateFirst(Query query, Update update, String collectionName);
/**
* Updates all objects that are found in thecollection for the entity class that matches the query document criteria
* with the provided updated document.
*
* @param query the query document thatspecifies the criteria used to select a record to be updated
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing
* object.
* @param entityClass class that determines thecollection to use
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupdateMulti(Query query, Update update, Class<?> entityClass);
/**
* Updates all objects that are found in thespecified collection that matches the query document criteria with the
* provided updated document.
*
* @param query the query document thatspecifies the criteria used to select a record to be updated
* @param update the update document thatcontains the updated object or $ operators to manipulate the existing
* object.
* @param collectionName name of the collectionto update the object in
* @return the WriteResult which lets youaccess the results of the previous write.
*/
WriteResultupdateMulti(Query query, Update update, String collectionName);
/**
* Remove the given object from the collectionby id.
*
* @param object
*/
voidremove(Object object);
/**
* Removes the given object from the givencollection.
*
* @param object
* @param collection must not be {@literalnull} or empty.
*/
voidremove(Object object, String collection);
/**
* Remove all documents that match the providedquery document criteria from the the collection used to store the
* entityClass. The Class parameter is alsoused to help convert the Id of the object if it is present in the query.
*
* @param <T>
* @param query
* @param entityClass
*/
<T> voidremove(Query query, Class<T> entityClass);
/**
* Remove all documents from the specifiedcollection that match the provided query document criteria. There is no
* conversion/mapping done for any criteriausing the id field.
*
* @param query the query document thatspecifies the criteria used to remove a record
* @param collectionName name of the collectionwhere the objects will removed
*/
voidremove(Query query, String collectionName);
/**
* Returns the underlying {@linkMongoConverter}.
*
* @return
*/
MongoConvertergetConverter();