新建maven项目
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gm.mongoDB</groupId>
<artifactId>mongoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build />
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.6.3</version>
</dependency>
</dependencies>
</project>
log4j.properties
### set log levels ###
log4j.rootLogger = debug , stdout, D , E
### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
###log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n
### 输出到日志文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
## 输出DEBUG级别以上的日志
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 保存Debug信息到单独文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
## 异常日志文件名
log4j.appender.D.File = logs/error.log
log4j.appender.D.Append = true
## 只输出ERROR级别以上的日志!!!
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 保存异常信息到单独文件 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [%p] - %m%n
MongoHelper
package com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoHelper {
private static final Logger logger = LoggerFactory
.getLogger(MongoHelper.class);
static final String DBName = "mydbs";
static final String ServerAddress = "192.168.174.200";
static final int PORT = 29017;
public MongoHelper() {
}
public MongoClient getMongoClient() {
MongoClient mongoClient = null;
try {
// 连接到 mongodb 服务
mongoClient = new MongoClient(ServerAddress, PORT);
logger.debug("Connect to mongodb successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return mongoClient;
}
public MongoDatabase getMongoDataBase(MongoClient mongoClient) {
MongoDatabase mongoDataBase = null;
try {
if (mongoClient != null) {
// 连接到数据库
mongoDataBase = mongoClient.getDatabase(DBName);
logger.debug("Connect to DataBase successfully");
} else {
throw new RuntimeException("MongoClient不能够为空");
}
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public MongoDatabase getMongoDataBase() {
MongoDatabase mongoDataBase = null;
try {
// 连接到数据库
mongoDataBase = getMongoDataBase(getMongoClient());
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public void closeMongoClient(MongoDatabase mongoDataBase,
MongoClient mongoClient) {
if (mongoDataBase != null) {
mongoDataBase = null;
}
if (mongoClient != null) {
mongoClient.close();
}
logger.debug("CloseMongoClient successfully");
}
}
MongoDao
package com;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
/**
* MongoDB数据操作接口
*
*/
public interface MongoDao {
/**
* 根据id检索文档
*
* @param db
* @param table
* @param id
* @return
* @throws Exception
*/
public Map<String, Object> queryByID(MongoDatabase db, String table,
Object id) throws Exception;
/**
* 根据doc检索文档集合,当doc是空的时候检索全部
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public List<Map<String, Object>> queryByDoc(MongoDatabase db, String table,
BasicDBObject doc) throws Exception;
/**
* 检索全部返回集合
*
* @param db
* @param table
* @return
* @throws Exception
*/
public List<Map<String, Object>> queryAll(MongoDatabase db, String table)
throws Exception;
/**
* 遍历迭代器返回文档集合
*
* @param iterable
* @return
* @throws Exception
*/
public List<Document> findIterable(FindIterable<Document> iterable)
throws Exception;
/**
* 插入文档
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public boolean insert(MongoDatabase db, String table, Document doc)
throws Exception;
/**
* 插入多条文档
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public boolean insertMany(MongoDatabase db, String table, List<Document> doc)
throws Exception;
/**
* 删除文档
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public boolean delete(MongoDatabase db, String table, BasicDBObject doc)
throws Exception;
/**
* 删除单条文档
*
* @param db
* @param table
* @param doc
* @return
* @throws Exception
*/
public boolean deleteOne(MongoDatabase db, String table, BasicDBObject doc)
throws Exception;
/**
* 修改文档
*
* @param db
* @param table
* @param oldDoc
* @param newDoc
* @return
* @throws Exception
*/
public boolean update(MongoDatabase db, String table, BasicDBObject oldDoc,
BasicDBObject newDoc) throws Exception;
/**
* 修改单条文档
*
* @param db
* @param table
* @param whereDoc
* @param updateDoc
* @return
* @throws Exception
*/
public boolean updateOne(MongoDatabase db, String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) throws Exception;
/**
* 创建集合
*
* @param db
* @param table
* @throws Exception
*/
public void createCol(MongoDatabase db, String table) throws Exception;
/**
* 删除集合
*
* @param db
* @param table
* @throws Exception
*/
public void dropCol(MongoDatabase db, String table) throws Exception;
}
MongoDaoImpl
package com;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
/**
* MongoDB数据操作实现类
*
*/
public class MongoDaoImpl implements MongoDao {
private static final Logger logger = LoggerFactory
.getLogger(MongoDaoImpl.class);
public Map<String, Object> queryByID(MongoDatabase db, String table,
Object id) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
BasicDBObject query = new BasicDBObject("_id", id);
// DBObject接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,是key-value的数据结构,用起来和HashMap是基本一致的。
FindIterable<Document> iterable = collection.find(query);
Map<String, Object> jsonStrToMap = null;
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);// 这里用到我自己写的方法,主要是包json字符串转换成map格式,为后面做准备,方法放在后面
}
logger.debug("检索ID完毕,db:{},table:{},id:{} ", db.getName(), table, id);
return jsonStrToMap;
}
public List<Map<String, Object>> queryByDoc(MongoDatabase db, String table,
BasicDBObject doc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find(doc);
/**
* 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document>
* 3.通过游标遍历检索出的文档集合
* */
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map<String, Object> jsonStrToMap = JsonStrToMap
.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
logger.debug("检索doc完毕,db:{},table:{},doc:{} ", db.getName(), table,
doc.toJson());
return list;
}
public List<Map<String, Object>> queryAll(MongoDatabase db, String table) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
Map<String, Object> jsonStrToMap = JsonStrToMap
.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
logger.debug("检索全部完毕,db:{},table:{}", db.getName(), table);
return list;
}
public List<Document> findIterable(FindIterable<Document> iterable) throws Exception {
List<Document> list = new ArrayList<Document>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document doc = cursor.next();
list.add(doc);
}
cursor.close();
return list;
}
public boolean insert(MongoDatabase db, String table, Document doc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
collection.insertOne(doc);
long count = collection.count(doc);
if (count >= 1) {
logger.debug("文档插入成功,影响条数:{},db:{},table:{},doc:{} ", count,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档插入失败,影响条数:{},db:{},table:{},doc:{} ", count,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean insertMany(MongoDatabase db, String table, List<Document> doc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
long preCount = collection.count();
collection.insertMany(doc);
long nowCount = collection.count();
if ((nowCount - preCount) == doc.size()) {
logger.debug("文档插入成功,影响条数:{},db:{},table:{}", doc.size(),
db.getName(), table);
return true;
} else {
logger.debug("文档插入失败,影响条数:{},db:{},table:{}",
(nowCount - preCount), db.getName(), table);
return false;
}
}
public boolean delete(MongoDatabase db, String table, BasicDBObject doc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
DeleteResult deleteManyResult = collection.deleteMany(doc);
long deletedCount = deleteManyResult.getDeletedCount();
if (deletedCount > 0) {
logger.debug("文档删除成功,影响条数:{},db:{},table:{},doc:{} ", deletedCount,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档删除失败,影响条数:{},db:{},table:{},doc:{} ", 0,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean deleteOne(MongoDatabase db, String table, BasicDBObject doc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
DeleteResult deleteOneResult = collection.deleteOne(doc);
long deletedCount = deleteOneResult.getDeletedCount();
System.out.println("删除的数量: " + deletedCount);
if (deletedCount == 1) {
logger.debug("文档删除成功,影响条数:{},db:{},table:{},doc:{} ", deletedCount,
db.getName(), table, doc.toJson());
return true;
} else {
logger.debug("文档删除失败,影响条数:{},db:{},table:{},doc:{} ", 0,
db.getName(), table, doc.toJson());
return false;
}
}
public boolean update(MongoDatabase db, String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
UpdateResult updateManyResult = collection.updateMany(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateManyResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount > 0) {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
modifiedCount, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return true;
} else {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
0, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return false;
}
}
public boolean updateOne(MongoDatabase db, String table,
BasicDBObject whereDoc, BasicDBObject updateDoc) throws Exception {
MongoCollection<Document> collection = db.getCollection(table);
UpdateResult updateOneResult = collection.updateOne(whereDoc,
new Document("$set", updateDoc));
long modifiedCount = updateOneResult.getModifiedCount();
System.out.println("修改的数量: " + modifiedCount);
if (modifiedCount == 1) {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
1, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return true;
} else {
logger.debug(
"文档更新成功,影响条数:{},db:{},table:{},whereDoc:{},updateDoc:{} ",
0, db.getName(), table, whereDoc.toJson(),
updateDoc.toJson());
return false;
}
}
public void createCol(MongoDatabase db, String table) throws Exception {
db.createCollection(table);
logger.debug("集合创建成功,db:{},table:{}", db.getName(), table);
}
public void dropCol(MongoDatabase db, String table) throws Exception {
db.getCollection(table).drop();
logger.debug("集合删除成功,db:{},table:{}", db.getName(), table);
}
}