作者:逝去成回忆2502920253 | 来源:互联网 | 2014-05-28 16:53
MongoDB和Spring整合,根据开发文档找到对应的版本.根据官方文档知道Spring必须是3.0.x或以上的版本,MongoDB必须是1.6.5以上的版本才行。要想整合Spring和Mongodb必须下载相应的jar,这里主要是用到两种jar一种是spring-data-document和spring-data-
MongoDB和Spring整合,根据开发文档找到对应的版本.
根据官方文档知道Spring必须是3.0.x或以上的版本,MongoDB必须是1.6.5以上的版本才行。
要想整合Spring和Mongodb必须下载相应的jar,这里主要是用到两种jar一种是spring-data-document和spring-
data-commons两种类型的jar但是两种类型的jar版本必须匹配以免引起jar的冲突因为commons后面的版本jar目录有所改变所有版
本必须要对应好下面是jar下载地址
http://www.springsource.org/spring-data/mongodb
http://www.springsource.org/spring-data/commons
下面是我下载的jar还有就是添加mongodb java驱动包,spring
jar添加我就不多说了
Spring配置文件如下:
1.
2.
3.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4.
xmlns:cOntext="http://www.springframework.org/schema/context"
5.
xmlns:mOngo="http://www.springframework.org/schema/data/mongo"
6.
xsi:schemaLocation=
7.
"http://www.springframework.org/schema/context
8.
http://www.springframework.org/schema/context/spring-context-3.0.xsd
9.
http://www.springframework.org/schema/data/mongo
10. http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
11. http://www.springframework.org/schema/beans
12. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
13.
14.
15.
16.
17. class="org.springframework.data.document.mongodb.MongoTemplate">
18.
19.
20.
21.
22. class="com.mongo.repository.PersonRepository">
23.
24.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
定义增删查改的接口:
public interface ModuleStatService
{
//基本查询
ModuleDaily
queryModuleDaily(Long moduleId, String date);
//聚合查询
ModuleDaily
genModuleDaily(GeneralHierarchy module, String startDate, String
endDate);
}
实现接口类:
@Service
public class ModuleStatServiceImpl implements ModuleStatService {
@Resource
private MongoTemplate
productMongo;
@Autowired
private MongoTemplate commonMongo;
@Override
public ModuleDaily
queryModuleDaily(Long moduleId, String date) {
return productMongo.findOne(Query.query(Criteria.where("moduleId").is(moduleId).and("date").is(date)),
ModuleDaily.class,
Constant.COLLECTION_MODULE_DAILY);
}
public ModuleDaily
genModuleDaily(final GeneralHierarchy module, final String startDate, final String endDate) {
DBObject
result = commonMongo.execute(Constant.COLLECTION_URL_DAILY, new CollectionCallback() {
@Override
public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException {
List patterns = new ArrayList();
for (String anchor : module.getAnchors()) {
patterns.add(Pattern.compile(anchor));
}
// 设置Where条件
BasicDBObject matchOpt = new BasicDBObject();
Map matchMap = new HashMap();
matchMap.put("channel",
module.getSiteName());//设置where条件channel=""
matchMap.put("date", (new BasicDBObject("$gt",
startDate)).append("$lt", endDate)); //设置where条件date>=startDate
and date
matchMap.put("url", new BasicDBObject("$in", patterns));
//设置这则表达式,patterns是这则表达式数组,获取url匹配所有正则的数据
matchOpt.put("$match", new BasicDBObject(matchMap));
// 对分组字段统计行数且分组统计字段默认为返回结果集合
BasicDBObject groupOpt = new BasicDBObject();
Map groupMap = new HashMap();
groupMap.put("_id", "$date");
groupMap.put("totalPV", new BasicDBObject("$sum",
"$pv"));
groupMap.put("totalUV", new BasicDBObject("$sum",
"$uv"));
groupMap.put("totalDQ", new BasicDBObject("$sum",
"$dq"));
groupMap.put("totalRealUv", new BasicDBObject("$sum",
"$realUv"));
groupOpt.put("$group", new BasicDBObject(groupMap));
AggregationOutput aggrResult = collection.aggregate(matchOpt,
groupOpt);
Iterator iter =
aggrResult.results().iterator();
DBObject result = null;
while (iter.hasNext()) {
result =
iter.next();
break;
}
return result;
}
});
//提取结果集数据并处理给目标对象
ModuleDaily moduleDaily = new ModuleDaily();
moduleDaily.setModuleId(module.getId());
moduleDaily.setParentId(module.getParentId());
moduleDaily.setModuleName(module.getName());
if (result != null) {
moduleDaily.setPv((Long) result.get("totalPV"));
moduleDaily.setUv((Long) result.get("totalUV"));
moduleDaily.setDq((Long) result.get("totalDQ"));
moduleDaily.setRealUv((Long) result.get("totalRealUv"));
} else {
moduleDaily.setPv(0L);
moduleDaily.setUv(0L);
moduleDaily.setDq(0L);
moduleDaily.setRealUv((0L));
}
return moduleDaily;
}
}
以上实现类列举了基本的查询和聚合查询,在聚合查询中,分组字段默认为结果集字段,有时候分组字段不一定是聚合字段,这样需要通过DB类来处理,举例如下:
private static void test(DBCollection dBCollection) {
try {
DB db = dBCollection.getDB();
// 设置Where条件
DBObject match = new BasicDBObject("$match", new BasicDBObject("date", (new BasicDBObject("$gt",
"2012-11-28")).append("$lt", "2012-11-29")));
// 设置分组字段
BasicDBObject groupFilters = new BasicDBObject("_id",
"$PRIORITY");
// 对分组字段统计行数
groupFilters.put("count", new BasicDBObject("$sum", 1));
BasicDBObject group = new BasicDBObject("$group",
groupFilters);
// 设置显示的字段集合
DBObject fields = new BasicDBObject("PRIORITY", 1);
fields.put("_id", "$PRIORITY");
DBObject project = new BasicDBObject("$project",
fields);
//获取结果集
AggregationOutput output =
db.getCollection("messages").aggregate(match, project, group);
System.out.println(output.getCommandResult());
} catch (Exception e) {
e.printStackTrace();
}
}
总之,通过Spring整合MongoDB后,通过MongoTemplate很容易对mongodb进行增删查改,特别是利用正则表达式查询,能有效的根据业务需求聚合数据。