1.引入相关jar包
<dependency》
<groupId》 org.mongodb《/groupId>
<artifactId》 mongo-java-driver《/artifactId>
<version》 3.0.4《/version>
《/dependency>
2.部分实现源码
/**
* 不通过认证获取连接数据库对象
*
* @return
*/
public static MongoDatabase getConnect() {
//连接到 mongodb 服务
MongoClient mongoClient = new MongoClient(MONGO_HOST, MONGO_PORT);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(MONGO_DB_NAME);
//返回连接数据库对象
return mongoDatabase;
}
/**
* 需要密码认证方式连接
*
* @return
*/
public static MongoDatabase getConnect2() {
List<ServerAddress> adds = new ArrayList<>();
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress(MONGO_HOST, MONGO_PORT);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(MONGO_USERNAME, MONGO_DB_NAME, MONGO_PASSWORD.toCharArray());
credentials.add(mongoCredential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, credentials);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(MONGO_DB_NAME);
//返回连接数据库对象
return mongoDatabase;
}
/**
* 查询总条数
*/
public static Long getTotal(UserCoreRequest userCoreRequest) {
//获取数据库连接对象
MongoDatabase mongoDatabase = MongoDBUtil.getConnect2();
//获取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("persona");
//查询得到总条数
BasicDBObject searchCond = getFilterCondition(userCoreRequest);
return collection.count(searchCond);
}
/**
* 根据条件进行查询
*
* @return
*/
public static List<UserCoreVO> getUserCoreVOList(UserCoreRequest userCoreRequest) {
//获取数据库连接对象
MongoDatabase mongoDatabase = MongoDBUtil.getConnect2();
//获取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("persona");
//指定查询过滤器
MongoCursor cursor = filterCondition(userCoreRequest, collection);
List<UserCoreVO> userCoreVOList = new ArrayList<>();
while (cursor.hasNext()) {
//将_id属性值进行屏蔽
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"_id"});
//将json字符串转换为json对象
JSONObject obj = JSONObject.fromObject(cursor.next(), jsonConfig);
//将建json对象转换为Person对象
UserCoreVO userCoreVO = (UserCoreVO) JSONObject.toBean(obj, UserCoreVO.class);
userCoreVOList.add(userCoreVO);
}
return userCoreVOList;
}
private static MongoCursor filterCondition(UserCoreRequest userCoreRequest, MongoCollection<Document> collection){
BasicDBObject searchCond = getFilterCondition(userCoreRequest);
//分页进行查询
FindIterable findIterable = collection.find(searchCond).limit(userCoreRequest.getPageSize()).skip(userCoreRequest.getPageSize() * (userCoreRequest.getPageNum() - 1));
MongoCursor cursor = findIterable.iterator();
return cursor;
}