java操作mongodb

最近正在学习mongodb,自己整理了一下java对mongodb的基本操作。
package com.xzq.common;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.QueryBuilder;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;

/**
 * mongodb辅助类
 * 
 * @author xiazq
 * 
 */
public class MongodbHelper {

	private Mongo mongo;

	private DB db;

	private DBCollection dbCollection;

	public MongodbHelper(String ip, int port, String dbName) {
		try {
			this.mongo = new Mongo(ip, port);
			this.db = this.mongo.getDB(dbName);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new RuntimeException("连不上主机");
		}
	}

	public MongodbHelper(List<ServerAddress> serverList, String dbName) {
		this.mongo = new Mongo(serverList);
		this.db = this.mongo.getDB(dbName);
	}
	
	/**
	 * 指定用户连接
	 * @param ip
	 * @param port
	 * @param dbName
	 * @param username
	 * @param pwd
	 * @param poolSize
	 */
	public MongodbHelper(String ip, int port, String dbName, String username, String pwd) {
		try {
			this.mongo = new Mongo(ip, port);
			this.db = this.mongo.getDB(dbName);
			//指定用户
			db.authenticate(username, pwd.toCharArray());
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new RuntimeException("连不上主机");
		}
	}

	/**
	 * 如果集合不存在,则新建一个
	 * @param collectionName
	 * @return
	 */
	public DBCollection getDBCollection(String collectionName) {
		if(!db.collectionExists(collectionName)) {
			db.createCollection(collectionName, null);
		}
		this.dbCollection = this.db.getCollection(collectionName);
		return this.dbCollection;
	}
	
	public DBObject findOne() {
		return this.dbCollection.findOne();
	}
	
	public List<DBObject> findByDBObject(DBObject dbObject) {
		List<DBObject> lst = new ArrayList<DBObject>();
		DBCursor dbCursor = this.dbCollection.find(dbObject);
		while (dbCursor.hasNext()) {
			lst.add(dbCursor.next());
		}
		return lst;
	}

	/**
	 * 对指定键使用正则表达式查询
	 * @param key
	 * @param pattern
	 * @return
	 */
	public List<DBObject> findByPattern(String key, Pattern pattern) {
		DBObject dbObject = new BasicDBObject(key, pattern);
		return this.findByDBObject(dbObject);
	}
	
	public List<DBObject> findAll() {
		List<DBObject> lst = new ArrayList<DBObject>();
		DBCursor dbCursor = this.dbCollection.find();
		while (dbCursor.hasNext()) {
			lst.add(dbCursor.next());
		}
		return lst;
	}
	
	public boolean insert(DBObject dbObject) {
		WriteResult writeResult = this.dbCollection.insert(dbObject);
		if (writeResult.getN() > 0) {
			return true;
		}
		return false;
	}

	public void batchInsert(List<DBObject> lst) {
		this.dbCollection.insert(lst);
	}
	
	/**
	 * 修改
	 * @param queryObj 查询对象
	 * @param updateObj 更新对象
	 * @return
	 */
	public boolean update(DBObject queryObj, DBObject updateObj) {
		WriteResult writeResult = this.dbCollection.update(queryObj, updateObj);
		if (writeResult.getN() > 0) {
			return true;
		}
		return false;
	}
	
	public boolean delete(DBObject dbObject) {
		WriteResult writeResult = this.dbCollection.remove(dbObject);
		if (writeResult.getN() > 0) {
			return true;
		}
		return false;
	} 

	/**
	 * 添加用户,flag为true时,代表只读用户
	 * 通过shell查询用户:db.system.users.find()
	 * @param userName
	 * @param pwd
	 * @param flag
	 */
	public void addUser(String userName, String pwd, boolean flag) {
		this.db.addUser(userName, pwd.toCharArray(), flag);
	}
	
	/**
	 * 创建索引,1升序,-1降序
	 * @param index
	 */
	public void createIndex(DBObject index) {
		this.dbCollection.createIndex(index);
	}
	
	public List<DBObject> findAllIndex() {
		return this.dbCollection.getIndexInfo();
	}
	
	/**
	 * 根据索引名称删除索引
	 * @param name
	 */
	public void dropIndex(String name) {
		this.dbCollection.dropIndex(name);
	}
	
	/**
	 * 通过构建queryBuilder进行复杂查询
	 * @param builder
	 * @return
	 */
	public List<DBObject> findByQueryBuilder(QueryBuilder builder) {
		return this.findByDBObject(builder.get());
	}
	
	/**
	 * 根据查询条件,获取文档总数
	 * @param dbObject
	 * @return
	 */
	public long getCount(DBObject query) {
		if(query == null) {
			return this.dbCollection.getCount();
		}
		return this.dbCollection.getCount(query);
	}
	
	/**
	 * 分页查询
	 * @param query
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public List<DBObject> getList(DBObject query, int start, int pageSize) {
		DBCursor cursor = null;
		if(query == null) {
			cursor = this.dbCollection.find().skip(start).limit(pageSize);
		} else {
			cursor = this.dbCollection.find(query).skip(start).limit(pageSize);
		}
		List<DBObject> lst = new ArrayList<DBObject>();
		while (cursor.hasNext()) {
			lst.add(cursor.next());
		}
		return lst;
	}
}

单元测试类如下:

package com.xzq.common;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.bson.types.ObjectId;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;

public class MongodbDbHelperTest {

	//@Test
	public void insertTest1() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name", "张三");
		dbObject.put("age", 28);
		boolean flag = dbHelper.insert(dbObject);
		System.out.println("插入为:" + flag);
		System.out.println(dbHelper.findAll());
	}
	
	//@Test
	public void insertTest2() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id", new ObjectId("54b4bf558674d99c82e7cc1d"));
		dbObject.put("name", "张三");
		dbObject.put("age", 29);
		//当_ID存在时,插入不成功
		boolean flag = dbHelper.insert(dbObject);
		System.out.println("插入为:" + flag);
		System.out.println(dbHelper.findAll());
	}
	
	//@Test
	public void batchInsertTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		List<DBObject> lst = new ArrayList<DBObject>();
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name", "李四");
		dbObject.put("age", 29);
		lst.add(dbObject);
		dbObject = new BasicDBObject();
		dbObject.put("name", "李四老婆");
		dbObject.put("age", 27);
		lst.add(dbObject);
		dbObject = new BasicDBObject();
		dbObject.put("name", "李四儿子");
		dbObject.put("age", 3);
		lst.add(dbObject);
		dbHelper.batchInsert(lst);
		//通过正则表达式查询李四一家
		Pattern pattern = Pattern.compile("^李四");
		System.out.println(dbHelper.findByPattern("name", pattern));
	}
	
	//@Test
	public void updateTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		DBObject query = new BasicDBObject();
		//最好是通过_id来修改,类似关系数据库通过主键来修改
		query.put("_id", new ObjectId("54b4bf558674d99c82e7cc1d"));
		DBObject update = new BasicDBObject();
		update.put("name", "张三修改");
		update.put("age", 32);
		dbHelper.update(query, update);
		System.out.println(dbHelper.findAll());
	}
	
	//@Test
	public void deleteTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		DBObject delete = new BasicDBObject();
		delete.put("_id", new ObjectId("54b4bf558674d99c82e7cc1d"));
		dbHelper.delete(delete);
		System.out.println(dbHelper.findAll());
	}
	
	//@Test
	public void addUserTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.addUser("xzq", "123", false);
	}
	
	//@Test
	public void indexTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		DBObject index = new BasicDBObject();
		index.put("name", 1);
		dbHelper.createIndex(index);
		List<DBObject> indexs = dbHelper.findAllIndex();
		for(DBObject obj : indexs) {
			System.out.println(obj);
		}
	}
	
	//@Test
	public void findByQueryBuilderTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		QueryBuilder builder = new QueryBuilder();
		//查询:name = 张三
		builder.put("name").is("张三");
		//查询:name != 张三
		builder.put("name").notEquals("张三");
		//and是与操作(or是或操作),greaterThanEquals是大于等于,lessThan就是小于
		builder.and("age").greaterThanEquals(25).and("age").lessThanEquals(30);
		List<DBObject> lst = dbHelper.findByQueryBuilder(builder);
		for(DBObject obj : lst) {
			System.out.println(obj);
		}
		builder = new QueryBuilder();
		//in查询
		int[] ages = {20,27,30};
		builder.put("age").in(ages);
		lst = dbHelper.findByQueryBuilder(builder);
		for(DBObject obj : lst) {
			System.out.println(obj);
		}
	}
	
	@Test
	public void pageTest() {
		MongodbHelper dbHelper = new MongodbHelper("127.0.0.1", 27017, "test");
		dbHelper.getDBCollection("mytest12");
		long count = dbHelper.getCount(null);
		System.out.println(count);
		//每页2条数据,查询第二页
		List<DBObject> lst = dbHelper.getList(null, 2, 2);
		for(DBObject obj : lst) {
			System.out.println(obj);
		}
		DBObject query = new BasicDBObject();
		query.put("name", "李四");
		count = dbHelper.getCount(query);
		System.out.println(count);
		//每页2条数据,查询第一页
		lst = dbHelper.getList(query, 0, 2);
		for(DBObject obj : lst) {
			System.out.println(obj);
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值