基础实体类
@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. DOM 操作的常用 API 有哪些 ?

    DOM 操作的常用 API 就是DOM 通过API (接口)获取页面(html)元素: 1. 节点查询 API 1.1 document.querySelector()  选择第一个匹配的元素 1.2 ...

  2. 【Azure Cloud Service】使用Key Vault Secret添加.CER证书到Cloud Service Extended Support中

    问题描述 因为Key Vault的证书上传功能中,只支持pfx格式的证书,而中间证书,根证书不能转换为pfx格式,只能是公钥证书格式 cet 或者 crt,能通过文本工具直接查看base64编码内容. ...

  3. Go语言单元测试的执行

    Go 语言推荐测试文件和源代码文件放在同一目录下,测试文件以 _test.go 结尾.比如,当前 package 有 calc.go 一个文件,我们想测试 calc.go 中的 Add 和 Mul 函 ...

  4. Chrome 130 版本新特性& Chrome 130 版本发行说明

    Chrome 130 版本新特性& Chrome 130 版本发行说明 一.Chrome 130 版本浏览器更新 1. 新的桌面提示 Chrome 130 引入了一种新的 Toast 样式,用 ...

  5. php如何解决高并发

    PHP交流群  656679284  为PHP广大爱好者提供技术交流,有问必答,相互学习相互进步! 1.应用和静态资源分离 将静态资源(js,css,图片等)放到专门的服务器中. 2.页面缓存 将应用 ...

  6. 为什么在http协议中使用base64编码方式传输二进制文件

    相关: 图解 Base64 实现原理并使用 js 实现一个简单的 Base64 编码器 常用加密方法之Base64编解码及代码实现 一直都知道在http协议中使用base64的方式传递二进制文件,虽然 ...

  7. [转载] Ubuntu上Firefox字体太小--高分屏背锅——高清分辨率屏幕下浏览器设置

    版权声明:本文为CSDN博主「mythinker2」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明.原文链接:https://blog.csdn.net/myth ...

  8. Ymodem协议详解

    Xmodem.Ymodem和Zmodem协议是最常用的三种通信协议. Xmodem协议是最早的,传输128字节信息块. Ymodem是Xmodem的改进版协议,具有传输快速稳定的优点.它可以一次传输1 ...

  9. Docker for the Virtualization Admin

    Docker is one of the most successful open source projects in recent history, and organizations of al ...

  10. 内衣 ERP 系统 (Delphi)

    服装行业ERP系统,当时从开始实施推行,最后二次开发,源代码交接... 发几个截图看看 可配置的查询 这个功能几乎被我全改过... 后台报表配置 欢迎微信搜一搜 IT软件部落 关注公众号,你可以了解更 ...