max和min的测试:
@Test
public void testMaxAndMinAge() throws Exception {
Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
Person result = mongoTemplate.findOne(q, Person.class);
log.info(result);
q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
result = mongoTemplate.findOne(q, Person.class);
log.info(result);
}
distinct的测试:
@Test
public void testDistinct() throws Exception {
List result = mongoTemplate.getCollection("person").distinct("myFriends");
for (Object o : result) {
log.info(o);
}
log.info("==================================================================");
Query query = Query.query(Criteria.where("manId").is("123456"));
result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
for (Object o : result) {
log.info(o);
}
log.info("==================================================================");
result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
for (Object o : result) {
log.info(o);
}
}
输出的结果为:
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
这里我要特别说明一下, 当使用了Spring Data Mongo,如上面的findOne(query, Person.class)它就会把查询的结果集转换成Person类的对象。Spring Data Mongo的很多API中都这样,让传入了一个Bean的class对象。因为distinct的测试是输出list<String>的,我使用的mongo-Java-driver的api。他们都很简单,唯一的是Query这个Spring提供的对象,希望读者注意,他几乎封装了所有条件查询,sort,limit等信息。query的api见:
其他的高级查询后续会补上。
相关阅读:MongoDB高级查询[聚合Group] http://www.linuxidc.com/Linux/2013-04/82788.htm
