MongoDB连接工具类

工具类


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

/**
 * MongoDB连接类
 * @author zql
 * @createTime 2020-11-30 23:53:48
 * @version 1.0
 *
 */
public class MongoConnection {
	
	private static MongoClient mongoClient;
	
	private static MongoClient mongoClient2;

	/**
	 * 不通过认证获取连接数据库对象
	 * @author zql
	 * @createTime 2020-11-30 23:53:26
	 *
	 * @param host 服务器地址
	 * @param port 端口
	 * @param dbaseName 连接到的数据库,若指定的数据库不存在,mongoDB将会在第一次插入文档时创建数据库。
	 * @return 返回连接数据库对象
	 */
	public static MongoDatabase getNoIdentifyConnect(String host, int port, String dbaseName) {
		// 连接到 mongodb 服务
		MongoConnection.mongoClient = new MongoClient(host, port);

		// 连接到数据库
		MongoDatabase mongoDatabase = MongoConnection.mongoClient.getDatabase(dbaseName);

		// 返回连接数据库对象
		return mongoDatabase;
	}

	/**
	 * 通过连接认证获取MongoDB连接
	 * @author zql
	 * @createTime 2020-11-30 23:52:57
	 *
	 * @param host 服务器地址
	 * @param port 端口
	 * @param dbaseName 连接到的数据库,若指定的数据库不存在,mongoDB将会在第一次插入文档时创建数据库。
	 * @param userName 用户名 
	 * @param password 密码
	 * @return 返回连接数据库对象
	 */
	public static MongoDatabase getIdentifyConnect(String host, int port, String dbaseName, String userName, String password) {

		List<ServerAddress> adds = new ArrayList<ServerAddress>();

		ServerAddress serverAddress = new ServerAddress(host, port);
		adds.add(serverAddress);

		List<MongoCredential> credentials = new ArrayList<>();

		MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, dbaseName,
				password.toCharArray());
		credentials.add(mongoCredential);

		// 通过连接认证获取MongoDB连接
		MongoConnection.mongoClient2 = new MongoClient(adds, credentials);

		MongoDatabase mongoDatabase = MongoConnection.mongoClient2.getDatabase(dbaseName);

		return mongoDatabase;
	}
	
	/**
	 * 关闭连接
	 */
	public static void closeNoIdentifyConnect () {
		MongoConnection.mongoClient.close();
	}
	
	/**
	 * 关闭连接
	 */
	public static void closeIdentifyConnect () {
		MongoConnection.mongoClient2.close();
	}

	/**
	 * 插入一个文档
	 * @author zql
	 * @createTime 2020-11-30 23:52:36
	 *
	 * @param data 要插入的数据
	 * @param mongoDatabase 连接数据库对象
	 * @param col 插入的集合,如果指定的集合不存在,mongoDB将会在第一次插入文档时创建集合。
	 */
	public static void insertOne (Map<String, Object> data, MongoDatabase mongoDatabase, String col) {
	    //获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    
	    //创建文档
	    Document document = new Document();
	    
	    for (Map.Entry<String, Object> m : data.entrySet()) {
	    	document.append(m.getKey(), m.getValue()).append(m.getKey(), m.getValue());
	    }
	    
	    //插入一个文档
	    collection.insertOne(document);
	}
	
	/**
	 * 插入多个文档
	 * @author zql
	 * @createTime 2020-11-30 23:52:17
	 *
	 * @param listData 要插入的数据
	 * @param mongoDatabase 连接数据库对象
	 * @param col 插入的集合,如果指定的集合不存在,mongoDB将会在第一次插入文档时创建集合。
	 */
	public static void insertMany (List<Map<String, Object>> listData, MongoDatabase mongoDatabase, String col) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    
	    //要插入的数据
	    List<Document> list = new ArrayList<>();
	    for (Map<String, Object> data : listData) {
	    	//创建文档
		    Document document = new Document();
		    
		    for (Map.Entry<String, Object> m : data.entrySet()) {
		    	document.append(m.getKey(), m.getValue());
		    }
		    list.add(document);
	    }
	    
	    //插入多个文档
	    collection.insertMany(list);
	}
	
	/**
	 * 删除匹配到的第一个文档
	 * @author zql
	 * @createTime 2020-11-30 23:51:56
	 *
	 * @param col 删除的集合
	 * @param key 删除条件的键
	 * @param value 删除条件的值
	 * @param mongoDatabase 连接数据库对象
	 */
	public static void delectOne (String col, String key, Object value, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //申明删除条件
	    Bson filter = Filters.eq(key, value);
	    //删除与筛选器匹配的单个文档
	    collection.deleteOne(filter);
	}
	
	/**
	 * 删除匹配的所有文档
	 * @author zql
	 * @createTime 2020-11-30 23:50:59
	 *
	 * @param col 删除的集合
	 * @param key 删除条件的键
	 * @param value 删除条件的值 
	 * @param mongoDatabase 连接数据库对象
	 */
	public static void deleteMany (String col, String key, Object value, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //申明删除条件
	    Bson filter = Filters.eq(key, value);
	    //删除与筛选器匹配的所有文档
	    collection.deleteMany(filter);
	}
	
	/**
	 * 删除集合中所有文档
	 * @author zql
	 * @createTime 2020-11-30 23:51:19
	 *
	 * @param col
	 * @param mongoDatabase
	 */
	public static void deleteAllDocument(String col, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    collection.deleteMany(new Document());
	}
	
	/**
	 * 删除文档和集合。
	 * @author zql
	 * @createTime 2020-11-30 23:51:27
	 *
	 * @param col
	 * @param mongoDatabase
	 */
	public static void deleteAllCollection(String col, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    collection.drop();
	}
	
	/**
	 * 修改单个文档,修改过滤器筛选出的第一个文档
	 * @author zql
	 * @createTime 2020-11-30 23:50:12
	 *
	 * @param col 修改的集合
	 * @param key 修改条件的键
	 * @param value 修改条件的值
	 * @param eqKey 要修改的键,如果eqKey不存在,则新增记录
	 * @param eqValue 要修改的值
	 * @param mongoDatabase 连接数据库对象
	 */
	public static void updateOne (String col, String key, Object value,String eqKey, Object eqValue, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //修改过滤器
	    Bson filter = Filters.eq(key, value);
	    //指定修改的更新文档
	    Document document = new Document("$set", new Document(eqKey, eqValue));
	    //修改单个文档
	    collection.updateOne(filter, document);
	}
	
	/**
	 * 修改多个文档
	 * @author zql
	 * @createTime 2020-11-30 23:49:40
	 *
	 * @param col 修改的集合
	 * @param key 修改条件的键
	 * @param value 修改条件的值
	 * @param eqKey 要修改的键,如果eqKey不存在,则新增记录
	 * @param eqValue 要修改的值
	 * @param mongoDatabase 连接数据库对象
	 */
	public static void updateMany (String col, String key, Object value, String eqKey, Object eqValue, MongoDatabase mongoDatabase) {
		//获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //修改过滤器
	    Bson filter = Filters.eq(key, value);
	    //指定修改的更新文档
	    Document document = new Document("$set", new Document(eqKey, eqValue));
	    //修改多个文档
	    collection.updateMany(filter, document);
	}
	
	/**
	 * 查找集合中的所有文档
	 * @author zql
	 * @createTime 2020-11-30 23:49:15
	 *
	 * @param col 要查询的集合
	 * @param mongoDatabase 连接数据库对象
	 * @return
	 */
	public static MongoCursor<Document> find (String col, MongoDatabase mongoDatabase) {
	    //获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //查找集合中的所有文档
	    FindIterable<Document> findIterable = collection.find();
	    MongoCursor<Document> cursorIterator = findIterable.iterator();
	    return cursorIterator;
	}
	
	/**
	 * 按条件查找集合中文档
	 * @author zql
	 * @createTime 2020-11-30 23:48:44
	 *
	 * @param col 要查询的集合
	 * @param key
	 * @param value
	 * @param mongoDatabase 连接数据库对象
	 * @return
	 */
	public static MongoCursor<Document> Filterfind (String col,String key, Object value, MongoDatabase mongoDatabase) {
	    //获取集合
	    MongoCollection<Document> collection = mongoDatabase.getCollection(col);
	    //指定查询过滤器
	    Bson filter = Filters.eq(key, value);
	    
	    //指定查询过滤器查询
	    FindIterable<Document> findIterable = collection.find(filter);
	    MongoCursor<Document> cursorIterator = findIterable.iterator();
	    return cursorIterator;
	}
}

测试类

import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MongoDB连接测试类
 *
 * @author zql
 * @version 1.0
 * @createTime 2021-01-02 22:43:00
 * @modifyLog
 */
public class MongoConnectionTest {

    @Test
    public void insertOne() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        Map<String, Object> m1 = new HashMap<String, Object>();
        m1.put("姓名", "赵一");
        m1.put("性别", "男");
        m1.put("年龄", 18);
        MongoConnection.insertOne(m1, mongoDatabase, "user");

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void insertMany() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");
        Map<String, Object> m1 = new HashMap<String, Object>();
        m1.put("姓名", "张三");
        m1.put("性别", "男");
        m1.put("年龄", 18);
        Map<String, Object> m2 = new HashMap<String, Object>();
        m2.put("姓名", "李四");
        m2.put("性别", "女");
        m2.put("年龄", 17);
        List<Map<String, Object>> listData = new ArrayList<>();
        listData.add(m1);
        listData.add(m2);
        MongoConnection.insertMany(listData, mongoDatabase, "user");

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void delectOne() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");
        MongoConnection.delectOne("user", "姓名", "张三改", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void deleteMany() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        MongoConnection.deleteMany("user", "姓名", "张三", mongoDatabase);
        MongoConnection.deleteMany("user", "姓名", "李四", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void deleteAllDocument() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        MongoConnection.deleteAllDocument("user", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void deleteAllCollection() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        MongoConnection.deleteAllCollection("user", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void updateOne() {
        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        MongoConnection.updateOne("user", "姓名", "张三","姓名改", "张三改1", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void updateMany() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");

        MongoConnection.updateMany("user", "姓名", "张三", "姓名改", "张三改5", mongoDatabase);

        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void find() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");
        MongoCursor<Document> mc = MongoConnection.find("user", mongoDatabase);

        while (mc.hasNext()) {
            Document d = mc.next();
            System.out.println(d + "  size: " + d.size());
        }
        MongoConnection.closeNoIdentifyConnect();
    }

    @Test
    public void filterfind() {
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoConnection.getNoIdentifyConnect("192.168.174.158", 27017, "test");
        MongoCursor<Document> mc = MongoConnection.Filterfind("user", "姓名", "张三", mongoDatabase);

        while (mc.hasNext()) {
            Document d = mc.next();
            System.out.println(d + "  size: " + d.size());
        }
        MongoConnection.closeNoIdentifyConnect();
    }
}

maven依赖

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.0.4</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值