基础实体类
@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();

mongodb和spring集成中MongoTemplate的总结是使用方法的更多相关文章

  1. Spring MVC中处理静态资源的多种方法

    处理静态资源,我想这可能是框架搭建完成之后Web开发的”头等大事“了. 因为一个网站的显示肯定会依赖各种资源:脚本.图片等,那么问题来了,如何在页面中请求这些静态资源呢? 还记得Spring MVC中 ...

  2. Spring MVC 中获取session的几种方法

    Spring MVC 中使用session是一种常见的操作,但是大家上网搜索一下可以看到获取session的方式方法五花八门,最近,自己终结了一下,将获取session的方法记录下来,以便大家共同学习 ...

  3. spring应用中多次读取http post方法中的流(附源码)

    一.问题简述 先说下为啥有这个需求,在基于spring的web应用中,一般会在controller层获取http方法body中的数据. 方式1: 比如http请求的content-type为appli ...

  4. 向Spring 容器中注入对象的几种方法

    1.使用@Bean 注解,用于注入第三方 jar 包到SpringIOC容器中. 2.使用 @Import({Order.class, Member.class, MyImportBeanDefini ...

  5. Spring AOP中使用args表达式访问目标方法的参数

    Spring AOP 的使用过程理解 首先,aop的使用场景介绍: 1.处理一些通用的非功能性的需求,不影响业务流程,比如说打印日志.性能统计.推送消息等: 2.aop无法拦截static.final ...

  6. 禁用 Spring Boot 中引入安全组件 spring-boot-starter-security 的方法

    1.当我们通过 maven 或 gradle 引入了 Spring boot 的安全组件 spring-boot-starter-security,Spring boot 默认开启安全组件,这样我们就 ...

  7. 使用MongoDB的Spring Boot和MongoTemplate教程

    在本教程中,我们将构建一个Spring Boot应用程序,该应用程序演示如何使用MongoTemplate API访问MongoDB数据库中的数据. 对于MongoDB,我们将使用mLab,它提供了M ...

  8. spring框架中一个跟String的trim方法一样的方法

    @Test public void testTrimWhitespace() throws Exception { assertEquals(null, StringUtils.trimWhitesp ...

  9. Spring MVC中如何指定某个类或方法自适配地响应某个HTTP请求?

    方法已经找到,即调用AbstractHandlerMethodAdapter.handle() public final ModelAndView handle(HttpServletRequest  ...

  10. Spring Boot中快速操作Mongodb

    Spring Boot中快速操作Mongodb 在Spring Boot中集成Mongodb非常简单,只需要加入Mongodb的Starter包即可,代码如下: <dependency> ...

随机推荐

  1. 墨天轮国产数据库沙龙 | 四维纵横姚延栋 :MatrixDB,All-in-One高性能时序数据库

    分享嘉宾:姚延栋 北京四维纵横数据有限公司创始人.原Greenplum 北京研发中心总经理.Greenplum中国开源社区创始人.PostgreSQL中文社区常委.壹零贰肆数字基金会(非营利组织)联合 ...

  2. 记一次pip/pip3安装uwsgi报错

    背景 本来是想着在centos 7.9的主机上面部署一个flask应用,采用的方式是linux+nginx+uwsgi来进行发布,其他的都没有问题,但是在使用pip安装uwsgi时报错了,安装不成功, ...

  3. C/C++ volatile restrict 用法

    volatile和restrict是C和C++中的两个关键字,都用于指示编译器优化. volatile volatile的本意是"易变的",用法和const一样: volatile ...

  4. C语言之输入输出

    标准库 IO 输入输出功能并非C语言的组成部分,ANSI标准定义了相关的库函数 输入输出 <stdio.h> 流stream是与设备关联的数据的源或者目的地. 文本流:由文本行组成的序列 ...

  5. Java高并发synchronized讲解生产者消费者

    问题描述 题目:两个线程操作一个变量,实现两个线程对同一个资源一个进行加1操作,另外一个进行减1操作,且需要交替实现,变量的初始值为0.即两个线程对同一个资源进行加一减一交替操作.话不多说,开干首先我 ...

  6. Java Z 垃圾收集器如何彻底改变内存管理

    大家好,我是 V 哥,今天的内容来聊一聊 ZGC,Java Z Garbage Collector(ZGC)是一个低延迟垃圾收集器,旨在优化内存管理,主要用于大内存应用场景.它通过以下几个关键创新,彻 ...

  7. 怎样在Windows 环境下安装Git附详细步骤图

    Git下载路径:https://git-scm.com/ [步骤] 在非C盘创建一个git_install作为git的安装目录,双击安装包,按下一步默认安装即可 (后面有时间来补充各个参数意思,目前按 ...

  8. Java后端请求想接收多个对象入参的数据方法

    在Java后端开发中,如果我们希望接收多个对象作为HTTP请求的入参,可以使用Spring Boot框架来简化这一过程.Spring Boot提供了强大的RESTful API支持,能够方便地处理各种 ...

  9. Rework:每个程序员都应该读的一本书

    来源: 萌萌的博客 每一个程序员都有改变世界的梦想,他们不甘平凡,他们想要与众不同,他们想要创立世界上最酷的公司,那具体该如何做呢?风靡全球的<Rework>将告诉你答案. 37signa ...

  10. Java垃圾回收器总结

    什么是Java垃圾回收器 Java垃圾回收器是Java虚拟机(JVM)的三个重要模块(另外两个是解释器和多线程机制)之一,为应用程序提供内存的自动分配(Memory Allocation).自动回收( ...