由于最近项目要使用mongodb来处理一些日志,提前学习了一下mongodb的一些基本用法,大概写了一些常用的。
开发环境为:WIN7-64,JDK7-64,MAVEN3.3.9-64,IDEA2017-64.
程序基本结构为:
下面贴出核心代码示例:
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestWebProjectMaven</groupId>
<artifactId>TestWebProjectMaven</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>TestWebProjectMaven Maven Webapp</name>
<!-- 设定主仓库 -->
<repositories>
<!-- nexus私服 -->
<repository>
<id>nexus-repos</id>
<name>Team Nexus Repository</name>
<url>http://192.168.200.205:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<!-- 设定插件仓库 -->
<pluginRepositories>
<pluginRepository>
<id>nexus-repos</id>
<name>Team Nexus Repository</name>
<url>http://192.168.200.205:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations-java5</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
<build>
<finalName>TestWebProjectMaven</finalName>
<!-- 设置properties文件编译到target目录中,不然读取不到配置文件 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**
public class MongodbUtil {
private static MongoClient MONGODB_CLIENT = null;
private static String MONGODB_IP = null;
private static Integer MONGODB_PORT = null;
private static String MONGODB_DATABASE_NAME = null;
private static String MONGODB_COLLECTION_NAME = null;
static{
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
try {
compositeConfiguration.addConfiguration(new PropertiesConfiguration("mongodb.properties"));
} catch (ConfigurationException e) {
e.printStackTrace();
}
MONGODB_IP = compositeConfiguration.getString("MONGODB_IP");
MONGODB_PORT = compositeConfiguration.getInt("MONGODB_PORT");
MONGODB_DATABASE_NAME = compositeConfiguration.getString("MONGODB_DATABASE_NAME");
MONGODB_COLLECTION_NAME = compositeConfiguration.getString("MONGODB_COLLECTION_NAME");
MONGODB_CLIENT = new MongoClient(MONGODB_IP,MONGODB_PORT);
}
private MongodbUtil() {
}
public static MongoDatabase getMongodbDatabase(){
return MONGODB_CLIENT.getDatabase(MONGODB_DATABASE_NAME);
}
public static void closeMongodbClient(){
if(null != MONGODB_CLIENT){
MONGODB_CLIENT.close();
MONGODB_CLIENT = null;
}
}
public static MongoCollection<Document> getMongoCollection(){
return getMongodbDatabase().getCollection(MONGODB_COLLECTION_NAME);
}
public static void insertOneCollectionByMap(Map<String,Object> map){
getMongoCollection().insertOne(handleMap(map));
}
public static void insertManyCollectionByMap(List<Map<String,Object>> listMap){
List<Document> list = new ArrayList<Document>();
for(Map<String,Object> map : listMap){
Document document = handleMap(map);
list.add(document);
}
getMongoCollection().insertMany(list);
}
public static void insertOneCollectionByModel(Object obj){
getMongoCollection().insertOne(handleModel(obj));
}
public static void insertManyCollectionByModel(List<Object> listObj){
List<Document> list = new ArrayList<Document>();
for(Object obj : listObj){
Document document = handleModel(obj);
list.add(document);
}
getMongoCollection().insertMany(list);
}
public static String queryCollectionByCondition(Document queryDocument,Document sortDocument,PageVO pageVO){
if(null == queryDocument || null == sortDocument || null == pageVO){
return null;
}else{
String returnList = getQueryCollectionResult(queryDocument,sortDocument,pageVO);
return returnList;
}
}
public static String queryCollectionByMap(Map<String,Object> map,Document sortDocument,PageVO pageVO){
String sql = getQueryCollectionResult(handleMap(map),sortDocument,pageVO);
return sql;
}
public static String queryCollectionByModel(Object obj,Document sortDocument,PageVO pageVO){
String sql = getQueryCollectionResult(handleModel(obj),sortDocument,pageVO);
return sql;
}
private static String getQueryCollectionResult(Document queryDocument,Document sortDocument,PageVO pageVO){
FindIterable<Document> findIterable = getMongoCollection().find(queryDocument)
.sort(sortDocument).skip((pageVO.getPageNum()-1)*pageVO.getPageSize()).limit(pageVO.getPageSize());
MongoCursor<Document> mongoCursor = findIterable.iterator();
StringBuilder sql = new StringBuilder();
Integer lineNum = 0;
while(mongoCursor.hasNext()){
sql.append("{");
Document documentVal = mongoCursor.next();
Set<Map.Entry<String,Object>> sets = documentVal.entrySet();
Iterator<Map.Entry<String,Object>> iterators = sets.iterator();
while(iterators.hasNext()){
Map.Entry<String,Object> map = iterators.next();
String key = map.getKey();
Object value = map.getValue();
sql.append("\"");
sql.append(key);
sql.append("\"");
sql.append(":");
sql.append("\"");
sql.append((value == null ? "" : value));
sql.append("\",");
}
sql.deleteCharAt(sql.lastIndexOf(","));
sql.append("},");
lineNum++;
}
//这里判断是防止上述没值的情况
if(sql.length() > 0){
sql.deleteCharAt(sql.lastIndexOf(","));
}
String returnList = getFinalQueryResultsSql(lineNum,sql.toString());
return returnList;
}
private static String getFinalQueryResultsSql(Integer lineNum,String querySql) {
StringBuilder sql = new StringBuilder();
sql.append("{");
sql.append("\"");
sql.append("jsonRoot");
sql.append("\"");
sql.append(":");
sql.append("\"");
sql.append(lineNum);
sql.append("\",");
sql.append("\"");
sql.append("jsonList");
sql.append("\"");
sql.append(":");
sql.append("[");
sql.append(querySql);
sql.append("]");
sql.append("}");
return sql.toString();
}
public static List<String> getALLCollectionNameOfList(){
List<String> list = new ArrayList<String>();
MongoIterable<String> mongoIterable = getMongodbDatabase().listCollectionNames();
for(String name : mongoIterable){
list.add(name);
}
return list;
}
public static Map<String,String> getALLCollectionNameOfMap() {
Map<String,String> map = new HashMap<String,String>();
MongoIterable<String> mongoIterable = getMongodbDatabase().listCollectionNames();
for(String name : mongoIterable){
map.put(name,name);
}
return map;
}
public static Integer queryCollectionCount(Document queryDocument){
int count = (int) getMongoCollection().count(queryDocument);
return count;
}
public static String queryCollectionModelById(String id){
ObjectId objectId = new ObjectId(id);//注意在处理主键问题上一定要用ObjectId转一下
Document document = getMongoCollection().find(Filters.eq("_id",objectId)).first();
return (document == null ? null : document.toJson());
}
public static void updateCollectionById(String id,Map<String,Object> updateMap){
Document queryDocument = new Document();
ObjectId objId = new ObjectId(id);//注意在处理主键问题上一定要用ObjectId转一下
queryDocument.append("_id", objId);
Document updateDocument = handleMap(updateMap);
getMongoCollection().updateOne(queryDocument,new Document("$set",updateDocument));
}
public static void updateCollectionByCondition(Document queryDocument,Document updateDocument,Boolean
ifInsert){
UpdateOptions updateOptions = new UpdateOptions();
updateOptions.upsert(ifInsert);
getMongoCollection().updateMany(queryDocument,new Document("$set",updateDocument),updateOptions);
}
public static Integer deleteCollectionById(String id){
ObjectId objectId = new ObjectId(id);
Bson bson = Filters.eq("_id",objectId);
DeleteResult deleteResult = getMongoCollection().deleteOne(bson);
int count = (int) deleteResult.getDeletedCount();
return count;
}
public static void deleteCollectionByMap(Map<String,Object> map){
getMongoCollection().deleteMany(handleMap(map));
}
public static void deleteCollectionByModel(Object obj){
getMongoCollection().deleteMany(handleModel(obj));
}
public static void deleteCollectionByDocument(Document document){
getMongoCollection().deleteMany(document);
}
private static Document handleModel(Object obj){
Document document = null;
if(obj != null){
document = new Document();
try {
Class clz = obj.getClass();
Field fields[] = clz.getDeclaredFields();
for(Field field : fields){
String fieldName = field.getName();
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName,clz);
Method method = propertyDescriptor.getReadMethod();
Object fieldValue = method.invoke(obj);
document.append(fieldName,(fieldValue == null ? "" : fieldValue));
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}else{
document = new Document("","");
}
return document;
}
private static Document handleMap(Map<String,Object> map){
Document document = null;
if(null != map){
document = new Document();
Set<String> sets = map.keySet();
Iterator<String> iterators = sets.iterator();
while(iterators.hasNext()){
String key = iterators.next();
Object value = map.get(key);
document.append(key,(value == null ? "" : value));
}
}else{
document = new Document("","");//这种设置查询不到任何数据
}
return document;
}
public static void dropDatabase(String databaseName){
MONGODB_CLIENT.dropDatabase(databaseName);
}
public static void dropCollection(String databaseName,String collectionName){
MONGODB_CLIENT.getDatabase(databaseName).getCollection(collectionName).drop();
}
public static void testquery(){
List<Integer> list = new ArrayList<Integer>();
list.add(20);
list.add(21);
list.add(22);
FindIterable<Document> findIterable =
//getMongoCollection().find(Filters.and(Filters.lt("num",22),Filters.gt("num",17)));
//getMongoCollection().find(Filters.in("num",17,18));
getMongoCollection().find(Filters.nin("num",list));
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
System.out.println(document.toJson());
}
}
}