public class MongodbUtil {
private static MongoClient mongoClient;
private static final Logger log = LoggerFactory.getLogger(MongodbUtil.class);
private static SysConfig sysConfig;
public static void init() {
String userName = sysConfig.getMdUserName();
String password = sysConfig.getMdPassword();
String host = sysConfig.getMdIp();
String dataBase = sysConfig.getMdDatabase();
int port = sysConfig.getMdPort();
MongoClientOptions clientOptions =
new MongoClientOptions.Builder()
.connectionsPerHost(sysConfig.getMdConnectionsPerHost())
.maxWaitTime(sysConfig.getMdMaxWaitTime())
.socketTimeout(sysConfig.getMdSocketTimeout())
.connectTimeout(sysConfig.getMdConnectTimeout())
.threadsAllowedToBlockForConnectionMultiplier(sysConfig.getMdThreadsAllowed())
.writeConcern(WriteConcern.SAFE)
.build();
List
Arrays.asList(MongoCredential.createCredential(
userName, dataBase, password.toCharArray()));
mongoClient = new MongoClient(new ServerAddress(host,port),lstCredentials, clientOptions);
}
/**
* 获取DB实例 - 指定DB
*
* @param dbName
* @return
*/
public static MongoDatabase getDB(String dbName) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* 获取collection对象 - 指定Collection
*
* @param collName
* @return
*/
public static MongoCollection
if (null == collName || "".equals(collName)) {
return null;
}
if (null == dbName || "".equals(dbName)) {
return null;
}
MongoCollection
return collection;
}
/** 统计指定集合的总数 */
public static int getCount(MongoCollection
int count = (int) coll.count();
return count;
}
/** 条件查询 */
public static MongoCursor
return coll.find(filter).iterator();
}
/** 分页查询 */
public static MongoCursor
return coll.find(filter).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
}
/**
* 查询最大最小值
* @param coll
* @param filter
* @param orderCol
* @param orderType -1:最大值;1:最小值
* @return
*/
public static MongoCursor
BasicDBObject orderObj = new BasicDBObject(orderCol,orde);
return coll.find(filter).sort(orderObj).limit(1).iterator();
}
/**
* 合并多条数据(有则更新,无则插入)
* @param coll
* @param queryCols 多个字段请用,分隔
* @param list
* @return
*/
public static int mergeList(MongoCollection
}