mongdb工具类
package e16wifi.statistic.com.mongodb;

import java.util.ArrayList;
import java.util.List; import org.bson.Document; import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase; import e16wifi.statistic.com.utils.DESUtil;
import e16wifi.statistic.com.utils.MongoDBProperty;
import e16wifi.statistic.com.utils.SysPropertyJdbc; public class MongoDBDao {
//数据库
private MongoDatabase database = null;
private DB get_db_credit = null;
private MongoCollection<Document> collection = null;
private DBCollection dbcollection = null;
private DBCursor dbCursor = null;
private MongoCursor<Document> cursor = null;
private FindIterable<Document> findIterable = null;
//客户端实例
private MongoClient mongoClient = null; /**
* 构造函数
* @throws Exception
*/
public MongoDBDao() throws Exception{
this.mongoClient =getMongoClient();
} public void getMongoDatabase(String dataBsae) throws Exception{
database = this.mongoClient.getDatabase(dataBsae);
} public void getDB(String dataBsae){
get_db_credit = this.mongoClient.getDB(dataBsae);
} public DBCollection getDBCollection(String dataBsae,String tableName){
getDB(dataBsae);
this.dbcollection = get_db_credit.getCollection(tableName);
return this.dbcollection ;
} public MongoCollection getMongoCollection(String dataBsae,String tableName) throws Exception{
getMongoDatabase(dataBsae);
this.collection = database.getCollection(tableName);
return this.collection;
} public MongoCursor<Document> getMongoCursor(String dataBsae,String tableName,BasicDBObject searchQueryCity,BasicDBObject sort) throws Exception{
getMongoCollection(dataBsae, tableName);
if(sort !=null){
this.cursor = this.collection.find(searchQueryCity).sort(sort).iterator();
}else{
this.cursor = this.collection.find(searchQueryCity).iterator();
} return cursor;
} public DBCursor getDBCursor(String dataBsae,String tableName,BasicDBObject searchQueryCity){
getDBCollection(dataBsae,tableName);
dbCursor = this.dbcollection.find(searchQueryCity);
return dbCursor;
} public FindIterable<Document> getFindIterable(String dataBsae,String tableName,BasicDBObject searchQueryCity,int page,int size, BasicDBObject sort) throws Exception{
getMongoCollection(dataBsae, tableName);
return findIterable = collection.find(searchQueryCity).skip(page).sort(sort)
.limit(size);
} public void closeDBCursor(){
dbCursor.close();
mongoClient.close();
} public void closeMongoCursor(){
cursor.close();
mongoClient.close();
} public void closeMongoClient(){
mongoClient.close();
}
/**
* 获取MONGODB客户端实例
*
* @return
* @throws Exception
*/
private MongoClient getMongoClient() throws Exception {
try {
// 解密用密钥
String sKey = SysPropertyJdbc.getProperty("jdbc.deskey")
.substring(4, 28); String sIp = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mip"));
int iPort = Integer.valueOf(DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mport")));
String sUser = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("muser"));
String sPasword = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mpassword"));
String sDbNm = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mdb")); // ===================================================//
List<ServerAddress> serverList = new ArrayList<ServerAddress>();
serverList.add(new ServerAddress(sIp, iPort));
// ===================================================//
List<MongoCredential> mcList = new ArrayList<MongoCredential>();
mcList.add(MongoCredential.createCredential(sUser, sDbNm,
sPasword.toCharArray()));
// ===================================================//
MongoClientOptions.Builder builder = MongoClientOptions.builder();
// 与目标数据库能够建立的最大connection数量为50
builder.connectionsPerHost(50);
// 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
builder.threadsAllowedToBlockForConnectionMultiplier(50);
// 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
// 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
// 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
builder.maxWaitTime(1000 * 60 * 2);
// 与数据库建立连接的timeout设置为1分钟
builder.connectTimeout(1000 * 60 * 1);
// ===================================================//
MongoClientOptions mco = builder.build();
return new MongoClient(serverList, mcList, mco);
} catch (Exception e) {
throw e;
}
} }

mongdb取数据,(包含分页)


 PageView pageView = new PageView();
CommonUtil commonUtil = new CommonUtil();
String cityCode = this.getPara("selCity");// 当前城市
if (StringUtils.isNullOrEmpty(cityCode)) {
cityCode = iSelCity + "";
}
// 分页信息开始
String page = StringUtils.isNullOrEmpty(this.getPara("sPage"))
? "1"
: this.getPara("sPage");
Integer curPage = Integer.parseInt(page);
pageView.setCurrentPage(curPage);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
logger.debug("START...");
Date date = new Date();// 取时间
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE, -1);// 把日期往后增加一天.整数往后推,负数往前移动
date = calendar.getTime();
// App用户基本信息
// mongoDB获取连接
MongoDBDao mongoClient = new MongoDBDao();
// 获取数据库
String mdb = DESUtil.decryptMode(
SysPropertyJdbc.getProperty("jdbc.deskey").substring(4, 28),
MongoDBProperty.getProperty("mdb")); BasicDBObject condition = new BasicDBObject();
condition.put("statDate", new BasicDBObject("$gte",matter2.parse(datestart)).append("$lte", matter2.parse(dateend))); //日期查询条件 查询时间范围 gt大于, lt小于 gte、ge大于等于   lte、le 小于等于
if (!"999".equals(cityCode)) {
condition.put("cityCode", cityCode);
}
BasicDBObject sort = new BasicDBObject();
// 1,表示正序; -1,表示倒序
sort.put("cityCode", 1);// 按照活跃度排名
MongoCursor<Document> cursor1 = mongoClient.getMongoCursor(mdb, "app_user_stat", condition,sort);
Integer i = 0;
try{
while (cursor1.hasNext()) {
cursor1.next();
i++;
}
} finally {
cursor1.close();
}
pageView.setTotal(i);
MongoCursor<Document> cursor = mongoClient.getFindIterable(mdb, "app_user_stat", condition, (curPage - 1) * pageView.getPageSize(), pageView.getPageSize(), sort).iterator();
List<Record> appDetail = new ArrayList<Record>();
try{
while (cursor.hasNext()) {
Iterator<Entry<String, Object>> iter = cursor.next().entrySet()
.iterator();
Record record = new Record();
while (iter.hasNext()) {
Entry eTmp = (Entry) iter.next();
Map colums = record.getColumns();
String sKeyTmp = eTmp.getKey().toString();
String sKeyValue = "";
if (eTmp.getValue() == null) {
sKeyValue = "0";
} else {
sKeyValue = eTmp.getValue().toString();
}
switch (sKeyTmp) {
case "statDate" :
if ("0".equals(sKeyValue)) {
colums.put("DATE", dateFormat.format(new Date()));
} else {
System.out.println("test" + sKeyValue);
colums.put("DATE",
dateFormat.format(eTmp.getValue()));
}
break;
case "cityName" :
// String cityName = TCity.dao
// .getCityInfoByCityCd(sKeyValue).get(0)
// .getStr("city_name");
colums.put("CITY", sKeyValue);
break;
case "userSum" :
colums.put("TOTALUSER", sKeyValue);
break;
case "newUserSum" :
colums.put("NEWADD", sKeyValue);
break;
case "activeUserDay" :
colums.put("ACTIVEDAY", sKeyValue);
break;
case "activeUserWeek" :
colums.put("ACTIVEWEEK", sKeyValue);
break;
case "activeUserMonth" :
colums.put("ACTIVEMONTH", sKeyValue);
break;
case "openTimes" :
colums.put("APPOPEN", sKeyValue);
break;
case "avgTimeDay" :
colums.put("AVGDAY", sKeyValue);
break;
case "avgTimeWeek" :
colums.put("AVGWEEK", sKeyValue);
break;
}
}
appDetail.add(record);
}
} finally {
cursor.close();
mongoClient.closeMongoClient();
}

 

MongoDBDao 工具类(包含分页取数据)的更多相关文章

  1. 借助Spring工具类如何实现支持数据嵌套的赋值操作

    假设有两个Bean A和B,想将B中的属性赋值到A实体中,可以使用get set来实现,当属性过多时,就会显得很冗余,可以使用spring提供的BeanUtils.copyProperties()来实 ...

  2. Java并发工具类之线程间数据交换工具Exchanger

    Exchanger是一个用于线程间协做的工具类,主要用于线程间的数据交换.它提供了一个同步点,在这个同步点,两个线程可以彼此交换数据.两个线程通过exchange方法交换数据,如果一个线程执行exch ...

  3. 利用BeanUtils工具类封装表单数据

    一.BeanUtils工具类的使用 1.首先导入BeanUtils工具类的jar包 commons-beanutils-1.8.0.jar commons-logging-1.1.1.jar 2.se ...

  4. 使用POI导出EXCEL工具类并解决导出数据量大的问题

    POI导出工具类 工作中常常会遇到一些图表需要导出的功能,在这里自己写了一个工具类方便以后使用(使用POI实现). 项目依赖 <dependency> <groupId>org ...

  5. 利用JDBC工具类添加和查询数据-Java(新手)

    JDBC工具类: 1 package cn.lxr.jdbclx; 2 3 import java.sql.*; 4 5 public class JDBCUtils { 6 private stat ...

  6. Javascript加载talbe(包含分页、数据下载功能)

    效果图如下: 首先简单说明一下,后面会给所涉及到的代码都贴上来的. 1.excel图标是一个用户控件,用来触发下载 2.首页.上页......每页多少条,这一块是一个整体,你可以选择放置在表格下面,或 ...

  7. SQL 2012 分页取数据

    ,), data int ) select * from t1 row rows only create clustered index t1c on t1(id) declare @i int ) ...

  8. php 循环从数据库分页取数据批量修改数据

    //批量修改email重复 public function getEmail() { $this->model = app::get('shop')->model('manage'); / ...

  9. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

随机推荐

  1. .Net语言 APP开发平台——Smobiler学习日志:Poplist控件的正确打开方式以及如何快速实现

    最前面的话:Smobiler是一个在VS环境中使用.Net语言来开发APP的开发平台,也许比Xamarin更方便 样式一 一.目标样式 我们要实现上图中的效果,需要如下的操作: 1.从工具栏上的&qu ...

  2. MFC AfxMessageBox默认标题修改

    在工程的资源String Table里面添加AFX_IDS_APP_TITLE,然后设置其值即可,AFX_IDS_APP_TITLE的值就是AfxMessageBox的标题

  3. [SQL Server] 特殊字符、上标、下标处理

    今天遇到一个问题是往 SQL Server 中导入像m².m³这样的单位数据,可是在 SQL Server 中查看到的都是 m2.m3,于是在网上查了一下资料,顺便摘录下来供日后查阅. 一  Wind ...

  4. WPF's Style BasedOn

    <Style x:Key="BasedStyle" BasedOn="{x:Null}" TargetType="{x:Type Control ...

  5. PHP中模拟JSONArray

    前面整理过一篇文章,描述php中的array与json的array和object的转换关系.http://www.cnblogs.com/x3d/p/php-json-array-object-typ ...

  6. web.xml中url-pattern的用法

    目录结构: // contents structure [-] url-pattern的三种写法 servlet匹配原则 filter匹配原则 语法错误的后果 参考文章 一.url-pattern的三 ...

  7. 一分钟搞定AlloyTouch图片轮播组件

    轮播图也涉及到触摸和触摸反馈,同时,AlloyTouch可以把惯性运动打开或者关闭,并且设置min和max为运动区域,超出会自动回弹. 除了一般的竖向滚动,AlloyTouch也可以支持横向滚动,甚至 ...

  8. 5.6 JS中基本包装类型

    为了便于操作基本类型值,ES还提供了三种特殊的引用类型,即(基本包装类型):Number,String,Boolean.这三种类型与前面介绍的引用类型相似,但同时也拥有基本数据类型的一些特性. 平时经 ...

  9. UITableViewCell定制

    UITableViewCell定制 效果       特点 1.可以添加不同的TableViewCell,可以定制不同的cell样式; 2.可以动态改变cell的高度; 3.可以随意摆放你cell的位 ...

  10. iOS 设置UILabel的行间距并自适应高度

    NSString *contentStr = @"总以为,在最初的地方,有一个最原来的我,就也会有一个最原来的你"; UILabel *tempLabel = [[UILabel ...