https://winterlei27.iteye.com/blog/2405225
Mongodb與spring集成 MongoRepository實(shí)現(xiàn)增刪改查和復(fù)雜查詢
與HibernateRepository類似,通過繼承MongoRepository接口,我們可以非常方便地實(shí)現(xiàn)對一個(gè)對象的增刪改查,要使用Repository的功能,先繼承MongoRepository接口,其中T為倉庫保存的bean類,TD為該bean的唯一標(biāo)識的類型,一般為ObjectId。之后在service中注入該接口就可以使用,無需實(shí)現(xiàn)里面的方法,spring會根據(jù)定義的規(guī)則自動生成。
例:
Java代碼?

public?interface?PersonRepository?extends?????
MongoRepository<Person,?ObjectId>{????
//這里可以添加額外的查詢方法?????
但是MongoRepository實(shí)現(xiàn)了的只是最基本的增刪改查的功能,要想增加額外的查詢方法,可以按照以下規(guī)則定義接口的方法。自定義查詢方法,格式為“findBy+字段名+方法后綴”,方法傳進(jìn)的參數(shù)即字段的值,此外還支持分頁查詢,通過傳進(jìn)一個(gè)Pageable對象,返回Page集合。
例:
Java代碼?

public?interface?PersonRepository?extends?????
MongoRepository<Person,?ObjectId>{????
//查詢大于age的數(shù)據(jù)??????
public?Page<Product>?findByAgeGreaterThan(int?age,Pageable?page)?;????
}????
下面是支持的查詢類型,每三條數(shù)據(jù)分別對應(yīng):(方法后綴,方法例子,mongodb原生查詢語句)
GreaterThan(大于)?
findByAgeGreaterThan(int age)?
{"age" : {"$gt" : age}}
LessThan(小于)?
findByAgeLessThan(int age)?
{"age" : {"$lt" : age}}
Between(在...之間)?
findByAgeBetween(int from, int to)?
{"age" : {"$gt" : from, "$lt" : to}}
IsNotNull, NotNull(是否非空)?
findByFirstnameNotNull()?
{"age" : {"$ne" : null}}
IsNull, Null(是否為空)?
findByFirstnameNull()?
{"age" : null}
Like(模糊查詢)?
findByFirstnameLike(String name)?
{"age" : age} ( age as regex)
(No keyword) findByFirstname(String name)?
{"age" : name}
Not(不包含)?
findByFirstnameNot(String name)?
{"age" : {"$ne" : name}}
Near(查詢地理位置相近的)?
findByLocationNear(Point point)?
{"location" : {"$near" : [x,y]}}
Within(在地理位置范圍內(nèi)的)?
findByLocationWithin(Circle circle)?
{"location" : {"$within" : {"$center" : [ [x, y], distance]}}}
Within(在地理位置范圍內(nèi)的)?
findByLocationWithin(Box box)?
{"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}
盡管以上查詢功能已經(jīng)很豐富,但如果還不能滿足使用情況的話可以用一下方法---基于mongodb原本查詢語句的查詢方式。
例:在原接口中加入
Java代碼?

@Query("{?'name':{'$regex':?2,'$options':'i'},?sales':?{'$gte':?1,'$lte':?2}}")????
public?Page<Product>?findByNameAndAgeRange(String?name,double?ageFrom,double?ageTo,Pageable?page);????
?注釋Query里面的就是mongodb原來的查詢語法,我們可以定義傳進(jìn)來的查詢參數(shù),通過坐標(biāo)定義方法的參數(shù)。
還可以在后面指定要返回的數(shù)據(jù)字段,如上面的例子修改如下,則只通過person表里面的name和age字段構(gòu)建person對象。?
Java代碼?

@Query(value="{?'name':{'$regex':?2,'$options':'i'},?sales':{'$gte':?1,'$lte':?2}}",fields="{?'name'?:?1,?'age'?:?1}")?????
public?Page<Product>?findByNameAndAgeRange(String?name,double?ageFrom,double?ageTo,Pageable?page);???