引入jar包:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.2</version>
</dependency>
工具类:
import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author panteng * @description * @date 17-5-3. */ public class MongoUtils { public static MongoClient mongoClient = null; static { String host = PropertiesUtil.pros.getProperty("mongoHost"); Integer port = Integer.parseInt(PropertiesUtil.pros.getProperty("mongoPort")); ServerAddress serverAddress = new ServerAddress(host, port); List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); serverAddresses.add(serverAddress); //线程池配置 MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); builder.maxConnectionIdleTime(30); //最大连接数 builder.minConnectionsPerHost(5); //最小连接数 builder.maxConnectionIdleTime(15000); //最大空闲连接时间 builder.connectTimeout(1000 * 10); //与数据库建立连接超时时间 builder.threadsAllowedToBlockForConnectionMultiplier(10);//每个线程的队列数目(等待数目) MongoClientOptions myOption = builder.build(); mongoClient = new MongoClient(serverAddresses, myOption); } public static boolean insert(String dbName, String collectionName, Document document) { MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName); //插入数据 mongoCollection.insertOne(document); return true; } public static List<String> query(String dbName, String collectionName, BasicDBObject queryObject) { List<String> ret = new ArrayList<String>(); MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName); FindIterable<Document> iter = mongoCollection.find(queryObject).projection(Document.parse("{"title":1,"url":1,"category":1}")); Iterator iterator = iter.iterator(); while (iterator.hasNext()) { Document document = (Document) iterator.next(); //System.out.println(document.toString()); ret.add(document.toString()); } return ret; } public static void delete(String dbName, String collectionName, BasicDBObject queryObject) { MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName); mongoCollection.deleteMany(queryObject); } public static void update(String dbName, String collectionName, BasicDBObject queryObject, BasicDBObject targetObject) { MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName); mongoCollection.updateMany(queryObject, targetObject); } public static void getSlaveOk() { } }
测试代码:
/* * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved */ package site.panteng.test.mongo; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.xiaomi.weather.utils.MongoUtils; import org.bson.Document; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * @author panteng * @description * @date 17-5-2. */ public class MongoDbTest { //原生mongo @Test public void testMongoDb() { System.out.println("========START========="); ServerAddress serverAddress = new ServerAddress("10.38.164.80", 27017); List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); serverAddresses.add(serverAddress); //线程池配置 MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); builder.maxConnectionIdleTime(30); //最大连接数 builder.minConnectionsPerHost(5); //最小连接数 builder.maxConnectionIdleTime(300); //最大空闲连接时间 builder.connectTimeout(1000 * 10); //与数据库建立连接超时时间 builder.threadsAllowedToBlockForConnectionMultiplier(10);//每个线程的队列数目(等待数目) MongoClientOptions myOption = builder.build(); //获取MongoDB连接 MongoClient mongoClient = new MongoClient(serverAddresses, myOption); //连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); System.out.println("Connect to database successfully"); //获取集合 MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("article"); Document document = Document.parse("{"test":"testInsert"}"); //插入数据 mongoCollection.insertOne(document); } @Test public void testQueryRegx() {//正则表达式 System.out.println("=======取文章======="); BasicDBObject queryObj = new BasicDBObject(); Pattern john = Pattern.compile("^.{0,50}(女神)"); queryObj.put("title", john); List<String> getStrs = MongoUtils.query("test", "article", queryObj); System.out.println("获取到的数目:" + getStrs.size()); } @Test public void testDelete() { BasicDBObject queryObj = new BasicDBObject(); queryObj.put("title", "主治腰间盘突出"); MongoUtils.delete("test", "article", queryObj); } @Test public void testUpdate() { BasicDBObject queryObj = new BasicDBObject(); queryObj.put("title", "时尚感爆棚的款式"); BasicDBObject targetObj = new BasicDBObject(); targetObj.put("$set", Document.parse("{summary:'时尚风格的衣服'}")); MongoUtils.update("test", "article", queryObj, targetObj); } @Test public void testInsert() { Document document = Document.parse("{"id":"1","testAr":"testAr"}"); MongoUtils.insert("test", "article", document); } @Test public void testQueryAndOr() { Long start = System.currentTimeMillis(); BasicDBObject queryObj = new BasicDBObject(); BasicDBObject condition1 = new BasicDBObject(); BasicDBObject condition2 = new BasicDBObject(); condition1.put("title", Pattern.compile("^.{0,50}(女人)")); condition2.put("title", Pattern.compile("^.{0,50}(男人)")); queryObj.put("$and", new BasicDBObject[]{condition1, condition2}); MongoUtils.query("test", "article", queryObj); Long end1 = System.currentTimeMillis(); System.out.println("耗时:" + (end1 - start)); MongoUtils.query("test", "article", queryObj); Long end2 = System.currentTimeMillis(); System.out.println("耗时:" + (end2 - end1)); MongoUtils.query("test", "article", queryObj); Long end3 = System.currentTimeMillis(); System.out.println("耗时:" + (end3 - end2)); } @Test public void testMongoTemplate() { } }