对于 MongoDB v2.6+
Spring.IO MongoDB 驱动程序最近添加了一个 TextCriteria,请参阅$text $search your Documents with Spring Data MongoDB
TextCriteria criteria = TextCriteria.forDefaultLanguage()
.matchingAny("coffee", "cake");
Query query = TextQuery.queryText(criteria)
.sortByScore()
.with(new PageRequest(0, 5));
List<CookingRecipe> recipes = template.find(query, CookingRecipe);
如果您使用的是Grails MongoDB GORM 插件,则从 3.0.2 开始,TextCriteria 在该 API 中不可用。
相反,您可以使用 mongodb api 来执行查询和分页:
// groovy/grails code... java code is very similar
BasicDBObject textSearch = new BasicDBObject('$text', new BasicDBObject('$search', 'cookie'))
BasicDBObject projection = new BasicDBObject('score', new BasicDBObject('$meta', 'textScore'))
BasicDBObject sort = new BasicDBObject('score', new BasicDBObject('$meta', 'textScore'))
DBCursor cursor = CookingRecipe.getCollection().find(textSearch, projection).sort(sort).skip(10).limit(5)