`
xurichusheng
  • 浏览: 336696 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

MongoDB 3 操作方法

阅读更多

 

MongoDB 数据库版本:3.0.6

jar 包:mongo-java-driver-3.1.0.jar   (见附件)。

 

数据源配置:

mongodb.soTimeOut=30000
mongodb.connectionsPerHost=500
mongodb.threadsBlock=30
mongodb.host=10.0.0.11
#mongodb.host=localhost
mongodb.port=27017
mongodb.database=dkpt
mongodb.collectionUrl=dkcollect
mongodb.batchSize=3000
mongodb.pool=100

  

MongodbUtils.java

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoWriteException;
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.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.techstar.plat.alarm.entity.DeviceWarn;
import com.techstar.plat.model.RealTimeData;

import org.bson.Document;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @ClassName: MongodbUtils.java
 * @description
 * 
 *              <pre>
 *             Mongodb 工具类
 *             封装基础的增删改查业务
 * </pre>
 * @author 
 * @company 
 * @date 2015-8-20
 * @version V1.0
 */
public class MongodbUtils {

	private static Map<String, String> propMap = CommonsTkywConstants.propMap;
	private static final Integer soTimeOut = Integer.parseInt(propMap
			.get("mongodb.soTimeOut"));
	private static final Integer connectionsPerHost = Integer.parseInt(propMap
			.get("mongodb.connectionsPerHost"));
	private static final Integer threadsBlock = Integer.parseInt(propMap
			.get("mongodb.threadsBlock"));
	private String host = propMap.get("mongodb.host");
	private int port = Integer.parseInt(propMap.get("mongodb.port"));
	private ExecutorService executor = Executors.newFixedThreadPool(100);

	private String database = propMap.get("mongodb.database");

	private String collectionUrl = propMap.get("mongodb.collectionUrl");

	/**
	 * 通过 ip,端口号,数据库,连接初始化mongodb实例
	 * 
	 * @param host
	 * @param port
	 * @param database
	 * @param collectionUrl
	 */
	public MongodbUtils(String host, int port, String database,
			String collectionUrl) {
		this.host = host;
		this.port = port;
		this.database = database;
		this.collectionUrl = collectionUrl;
	}

	/**
	 * 默认构造函数,使用配置文件中的参数进行初始化mongodb 实例
	 */
	public MongodbUtils() {
	}

	/**
	 * 通过配置文件和传入的collectionName初始化mongodb实例
	 * 
	 * @param collectionName
	 */
	public MongodbUtils(String collectionName) {
		this.collectionUrl = collectionName;
	}

	/**
	 * 获取mongodb连接实例
	 * 
	 * @return
	 */
	private MongoClient getMongoClient() {
		MongoClient mongoClient = new MongoClient(
				new ServerAddress(host, port), new MongoClientOptions.Builder()
						.socketTimeout(soTimeOut)
						.connectionsPerHost(connectionsPerHost)
						.threadsAllowedToBlockForConnectionMultiplier(
								threadsBlock).socketKeepAlive(true).build());
		return mongoClient;
	}

	/**
	 * 
	 * @return
	 */
	private MongoClient getSingleClient() {
		if (mongoClient == null) {
			mongoClient = new MongoClient(new ServerAddress(host, port),
					new MongoClientOptions.Builder()
							.socketTimeout(soTimeOut)
							.connectionsPerHost(connectionsPerHost)
							.threadsAllowedToBlockForConnectionMultiplier(
									threadsBlock).socketKeepAlive(true).build());
		}

		return mongoClient;
	}

	private static final int batchSize = Integer.parseInt(propMap
			.get("mongodb.batchSize")) * 3;

	// private static final int batchDeleteSize = batchSize * 10;

	/**
	 * 只存入key-value的简单数据,如果key相同不删除
	 * 
	 * @param map
	 */
	public void addMapString(Map<String, String> map) {
		if (map == null || map.size() == 0) {
			return;
		}
		List<Document> docs = new ArrayList<Document>();
		Document doc = new Document();
		for (String key : map.keySet()) {
			doc.put(key, map.get(key));
		}
		docs.add(doc);
		executor.execute(new MongodbTask(getMongoClient(), database,
				collectionUrl, docs));
	}

	/**
	 * 关闭mongodb 连接
	 */
	public void close() {
		if (mongoClient != null) {
			mongoClient.close();
			mongoClient = null;
		}

	}

	/**
	 * 只存入key-value的简单数据,如果key相同不删除
	 * 
	 * @param map
	 */
	public void addMapObject(Map<String, Object> map) {
		if (map == null || map.size() == 0) {
			return;
		}
		Document doc = new Document();
		doc.putAll(map);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		dbCollection.insertOne(doc);
	}

	/**
	 * <pre>
	 * 存入一条复杂键值都是String的数据,如果key相同删除以前的数据,并重新插入新数据
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 */
	public void addOrUpdateString(Map<String, String> argMap) {
		if (argMap == null || argMap.keySet() == null
				|| argMap.keySet().size() == 0) {
			return;
		}

		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		Document doc = new Document();
		Object keyV = argMap.get("key");
		if (keyV != null) {
			doc.put("key", keyV);
			try {
				dbCollection.deleteMany(doc);
			} catch (MongoWriteException e) {
			}
		}
		doc.putAll(argMap);
		dbCollection.insertOne(doc);
	}

	/**
	 * <pre>
	 * 存入一条复杂键值都是String的数据,如果key相同删除以前的数据,并重新插入新数据
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 * @param deleteKey
	 *            需要根据哪个key删除以前的数据
	 */
	public void addOrUpdateString(Map<String, String> argMap, String deleteKey) {
		if (argMap == null || argMap.keySet() == null
				|| argMap.keySet().size() == 0) {
			return;
		}
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		Document doc = new Document();
		Object keyV = argMap.get(deleteKey);
		if (keyV != null) {
			doc.put(deleteKey, keyV);
			try {
				dbCollection.deleteMany(doc);
			} catch (MongoWriteException e) {

			}
		}

		doc.putAll(argMap);
		dbCollection.insertOne(doc);
	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 * @param deleteKey
	 *            需要根据哪个key删除以前的数据
	 */
	public void batchAddOrUpdateString(List<Map<String, String>> listMap,
			String deleteKey) {
		List<Document> docs = new ArrayList<Document>();
		int size = listMap.size();
		int index = 0;
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		List<String> deleteList = new LinkedList<String>();
		for (Map<String, String> map : listMap) {
			Document doc = new Document();
			doc.putAll(map);
			index++;
			docs.add(doc);
			deleteList.add(map.get(deleteKey));
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs, deleteList));
				docs = new ArrayList<Document>();
				deleteList = new LinkedList<String>();
			}
		}
	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 */
	public void batchAddOrUpdateString(List<Map<String, String>> listMap) {
		// long start = System.currentTimeMillis();
		// sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		// System.out.println("sssssssss:" + sdf.format(new Date()));
		List<Document> docs = new LinkedList<Document>();
		int size = listMap.size();
		int index = 0;
		List<String> deleteList = new LinkedList<String>();

		index = 0;
		for (Map<String, String> map : listMap) {
			Document doc = new Document();
			doc.putAll(map);
			index++;
			docs.add(doc);
			deleteList.add(map.get("key"));
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs, deleteList));
				docs = new ArrayList<Document>();
				deleteList = new LinkedList<String>();
			}
		}
		// mongoClient.close();
	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据,
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 */
	public void batchAddOrUpdateObject(List<Map<String, Object>> listMap) {
		List<Document> docs = new ArrayList<Document>();
		int size = listMap.size();
		int index = 0;
		// mongoClient = getSingleClient();
		// mongodb = mongoClient.getDatabase(database);
		// dbCollection = mongodb.getCollection(collectionUrl);

		// Document deleteDoc = new Document();
		List<String> deleteList = new LinkedList<String>();

		// for (Map<String, Object> map : listMap) {
		// deleteList.add((String) map.get("key"));
		// index++;
		// if ((index != 0 && index % batchDeleteSize == 0) || index == size) {
		// deleteDoc = new Document();
		// deleteDoc.put("key", new Document("$in", deleteList));
		// dbCollection.deleteMany(deleteDoc);
		// deleteList = new LinkedList<String>();
		// }
		// }

		for (Map<String, Object> map : listMap) {
			Document doc = new Document();
			doc.putAll(map);
			index++;
			docs.add(doc);
			deleteList.add((String) map.get("key"));
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs, deleteList, "key"));
				docs = new ArrayList<Document>();
				deleteList = new LinkedList<String>();
			}
		}
		// mongoClient.close();
	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据,
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 * @param deleteKey
	 *            需要根据哪个key删除以前的数据
	 */
	public void addOrUpdateObject(Map<String, Object> argMap, String deleteKey) {
		List<Document> docs = new ArrayList<Document>();
		if (argMap == null || argMap.keySet() == null
				|| argMap.keySet().size() == 0) {
			return;
		}
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);

		Document doc = new Document();
		Object keyV = argMap.get(deleteKey);
		if (keyV != null) {
			doc.put(deleteKey, keyV);
			try {
				dbCollection.deleteMany(doc);
			} catch (MongoWriteException e) {

			}
		}
		doc.putAll(argMap);
		executor.execute(new MongodbTask(getMongoClient(), database,
				collectionUrl, docs));

	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据,
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 * @param deleteKey
	 *            需要根据哪个key删除以前的数据
	 */
	public void batchAddOrUpdateObject(List<Map<String, Object>> listMap,
			String deleteKey) {
		List<Document> docs = new ArrayList<Document>();
		int size = listMap.size();
		int index = 0;
		// MongoClient mongoClient = getSingleClient();
		// MongoDatabase mongodb = mongoClient.getDatabase(database);
		// MongoCollection<Document> dbCollection =
		// mongodb.getCollection(collectionUrl);

		// Document deleteDoc = new Document();
		List<String> deleteList = new LinkedList<String>();

		// for (Map<String, Object> map : listMap) {
		// deleteList.add((String) map.get(deleteKey));
		// index++;
		// if ((index != 0 && index % batchDeleteSize == 0) || index == size) {
		// deleteDoc = new Document();
		// deleteDoc.put("key", new Document("$in", deleteList));
		// dbCollection.deleteMany(deleteDoc);
		// deleteList = new LinkedList<String>();
		// }
		// }

		for (Map<String, Object> map : listMap) {
			Document doc = new Document();
			doc.putAll(map);
			index++;
			docs.add(doc);
			deleteList.add((String) map.get(deleteKey));
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs, deleteList, deleteKey));
				docs = new ArrayList<Document>();
				deleteList = new LinkedList<String>();
			}
		}

	}

	/**
	 * <pre>
	 * 存入复杂对象,如果key相同删除以前的数据,并重新插入新数据,
	 * 
	 * 其中Map中一个键固定为“key” 含义是cimId或cimid+量测类型
	 * </pre>
	 * 
	 * @param listMap
	 * @param deleteKey
	 *            需要根据哪个key删除以前的数据
	 */
	public void addOrUpdateObject(Map<String, Object> argMap) {
		List<Document> docs = new ArrayList<Document>();
		if (argMap == null || argMap.keySet() == null
				|| argMap.keySet().size() == 0) {
			return;
		}
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		Document doc = new Document();
		Object keyV = argMap.get("key");
		if (keyV != null) {
			doc.put("key", keyV);
			try {
				dbCollection.deleteMany(doc);
			} catch (MongoWriteException e) {

			}
		}
		for (String key : argMap.keySet()) {
			doc.put(key, argMap.get(key));
		}
		docs.add(doc);
		executor.execute(new MongodbTask(getMongoClient(), database,
				collectionUrl, docs));
	}

	/**
	 * 批量存入复杂对象,如果key相同不删除
	 * 
	 * @param listMap
	 */
	public void batchAddMapString(List<Map<String, String>> listMap) {

		List<Document> docs = new ArrayList<Document>();
		int size = listMap.size();
		int index = 0;
		for (Map<String, String> map : listMap) {
			Document doc = new Document();
			for (String key : map.keySet()) {
				doc.put(key, map.get(key));
			}
			index++;
			docs.add(doc);
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs));
				docs = new ArrayList<Document>();
			}
		}
	}

	/**
	 * 批量存入复杂对象,如果key相同不删除
	 * 
	 * @param listMap
	 */
	public void batchAddObject(List<Map<String, Object>> listMap) {
		List<Document> docs = new ArrayList<Document>();
		int size = listMap.size();
		int index = 0;
		for (Map<String, Object> map : listMap) {
			Document doc = new Document();
			for (String key : map.keySet()) {
				doc.put(key, map.get(key));
			}
			index++;
			docs.add(doc);
			if ((index != 0 && index % batchSize == 0) || index == size) {
				executor.execute(new MongodbTask(getMongoClient(), database,
						collectionUrl, docs));
				docs = new ArrayList<Document>();
			}
		}
	}

	/**
	 * 根据key获取值 供实时数据使用
	 * 
	 * 如果key是cimeId+量测类型:则返回值该量测类型的值
	 * 
	 * 量测类型含义:
	 * 
	 * <pre>
	 * P: 有功 
	 * Q :无功 
	 * U :电压 
	 * I: 电流
	 * S:开关、刀闸开合状态
	 * </pre>
	 * 
	 * @param key
	 * @return
	 */
	public String findByCimeIdType(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String value = (String) findDoc.get("value");
				return value;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}

		}

		return null;
	}

	/**
	 * <pre>
	 * 根据key获取值,如果有值则获取长度为2的数组,
	 * 其中array[0]是具体值,array[1]返回是否有效,0-无效,1-有效
	 * 如果查询不到值则返回为空
	 * 
	 * 如果key是cimeId+量测类型:则返回值该量测类型的值
	 * 
	 * 量测类型含义:
	 * 
	 * 
	 * P: 有功 
	 * Q :无功 
	 * U :电压 
	 * I: 电流
	 * S:开关、刀闸开合状态
	 * </pre>
	 * 
	 * @param key
	 * @return
	 */
	public String[] findValueValidByCimeIdType(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String[] values = new String[2];
				String value = (String) findDoc.get("value");
				values[0] = value;
				Object validO = (Object) findDoc.get("valid");
				if (validO != null) {
					String valid = (String) validO;
					values[1] = valid;
				}
				return values;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}

		}

		return null;
	}

	public MongoCollection<Document> getCollection() {
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		return dbCollection;
	}

	/**
	 * <pre>
	 * 根据key获取值,如果无效返回0000
	 * 
	 * 如果key是cimeId+量测类型:则返回值该量测类型的值
	 * 
	 * 量测类型含义:
	 * 
	 * P: 有功 
	 * Q :无功 
	 * U :电压 
	 * I: 电流
	 * S:开关、刀闸开合状态
	 * </pre>
	 * 
	 * @param key
	 * @return
	 */
	public String findValueByCimeIdType(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String value = (String) findDoc.get("value");
				Object validO = (Object) findDoc.get("valid");
				if (validO != null) {
					String valid = (String) validO;
					if (valid.equals("0")) {
						return "0000";
					}
				}
				return value;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}

		return null;
	}

	/**
	 * 删除集合数据
	 */
	public void drop() {
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		dbCollection.drop();
	}

	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	/**
	 * 根据key活动告警对象
	 * 
	 * @param key
	 * @return
	 */
	public DeviceWarn getWarn(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String value = String.valueOf(findDoc.get("value"));
				DeviceWarn warn = new DeviceWarn();
				String methodid = (String) findDoc.get("methodid");
				warn.setModelId(methodid);
				String name = (String) findDoc.get("name");
				warn.setName(name);
				warn.setCimId(key);

				Object timeO = findDoc.get("time");
				if (timeO != null) {
					String time = (String) timeO;
					warn.setValue(Double.parseDouble(value));

					try {
						warn.setAlarmDate(new Timestamp(sdf.parse(time)
								.getTime()));
					} catch (ParseException e) {
					}
				}
				return warn;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}

		}

		return null;
	}

	/**
	 * 根据cime+量测类型查询当前值及其对应时间,
	 * 
	 * @param key
	 * @return
	 */
	public RealTimeData findByCimeIdType4Alarm(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String value = String.valueOf(findDoc.get("value"));
				RealTimeData realTimeData = new RealTimeData();

				Object timeO = findDoc.get("time");
				if (timeO != null) {
					String time = (String) timeO;
					realTimeData.setValue(Double.parseDouble(value));
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					try {
						realTimeData.setTime(new Timestamp(sdf.parse(time)
								.getTime()));
					} catch (ParseException e) {
					}
				}
				return realTimeData;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}

		return null;
	}

	// /**
	// * 根据cimeID获取设备对象相关信息
	// *
	// * 数据长度是2:obj[0]是类型,obj[1]是一体化模型对象
	// *
	// * 如:obj[0]是AcLineDot,obj[1]一定时AcLineDotPO对象,对用用可以对obj[1]强制转换成AcLineDotPO
	// *
	// * @param key
	// * cime id
	// * @return
	// */
	// public Object[] findByCimeId(String key) {
	// Document doc = new Document();
	// doc.append("key", key);
	// FindIterable<Document> finds = dbCollection.find(doc);
	// MongoCursor<Document> cursor = finds.iterator();
	// if (cursor.hasNext()) {
	// Document findDoc = cursor.next();
	// String type = (String) findDoc.get("type");
	// Object obj = findDoc.get("obj");
	// Object[] objs = new Object[2];
	// objs[0] = type;
	// objs[1] = obj;
	// return objs;
	// }
	// return null;
	// }

	/**
	 * 根据条件查找数据
	 * 
	 * @param findArgs
	 * @return
	 */
	public List<Document> find(Map<String, Object> findArgs) {
		Document doc = new Document();
		for (String key : findArgs.keySet()) {
			doc.append(key, findArgs.get(key));
		}
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		List<Document> docs = new ArrayList<Document>();
		MongoCursor<Document> cursor = finds.iterator();
		try {
			while (cursor.hasNext()) {
				Document findDoc = cursor.next();
				docs.add(findDoc);
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}

		return docs.size() > 0 ? docs : null;
	}

	/**
	 * <pre>
	 * 根据key在历史表比较最近的2个版本数据值是否相同,
	 * 如果相同返回null,
	 * 如果不相同返回key
	 * </pre>
	 * 
	 * @param key
	 * @return
	 */
	public String compareWithLastValue(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc).limit(2)
				.sort(new BasicDBObject("time", -1));
		MongoCursor<Document> cursor = finds.iterator();
		String currentValue = null;// 获取当前值
		String lastTimeValue = null;// 获取上次值
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				currentValue = (String) findDoc.get("value");
			}

			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				lastTimeValue = (String) findDoc.get("value");
			}

			if (currentValue != null && !currentValue.trim().equals("")) {
				if (lastTimeValue != null && !lastTimeValue.trim().equals("")) {
					if (currentValue.equals(lastTimeValue)) {
						return null;
					} else {
						return key;
					}
				}
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}

		return null;
	}

	/**
	 * 根据key获取最新一条数据
	 * 
	 * @param key
	 * @return
	 */
	public String findLastValue(String key) {
		Document doc = new Document();
		doc.append("key", key);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		FindIterable<Document> finds = dbCollection.find(doc);
		MongoCursor<Document> cursor = finds.iterator();
		try {
			if (cursor.hasNext()) {
				Document findDoc = cursor.next();
				String value = (String) findDoc.get("value");
				return value;
			}
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}

		}

		return null;
	}

	/**
	 * 更新对象
	 * 
	 * @param filter
	 * @param update
	 * @return
	 */
	public long update(Map<String, Object> filter, Map<String, Object> update) {
		Document doc = new Document();
		for (String key : filter.keySet()) {
			doc.append(key, filter.get(key));
		}
		BasicDBObject updateDocument = new BasicDBObject();
		BasicDBObject newDocument = new BasicDBObject();
		for (String key : update.keySet()) {
			newDocument.append(key, update.get(key));
		}
		updateDocument.append("$set", newDocument);
		mongoClient = getSingleClient();
		mongodb = mongoClient.getDatabase(database);
		dbCollection = mongodb.getCollection(collectionUrl);
		UpdateResult result = dbCollection.updateMany(doc, updateDocument);
		long size = result.getMatchedCount();
		return size;
	}

	private MongoClient mongoClient = null;
	private MongoDatabase mongodb = null;
	private MongoCollection<Document> dbCollection = null;

	/**
	 * 删除对象
	 * 
	 * @param deleteArgs
	 * @return
	 */
	public long delete(Map<String, Object> deleteArgs) {
		Document doc = new Document();
		for (String key : deleteArgs.keySet()) {
			doc.put(key, deleteArgs.get(key));
		}
		DeleteResult result = null;

		try {
			mongoClient = getSingleClient();
			mongodb = mongoClient.getDatabase(database);
			dbCollection = mongodb.getCollection(collectionUrl);
			result = dbCollection.deleteMany(doc);
			long size = result.getDeletedCount();
			return size;
		} catch (MongoWriteException e) {

		}
		return 0;
	}
}

 

分享到:
评论

相关推荐

    MongoDB Java操作大全 源代码 实例

    MongoDB Java操作大全 源代码 实例

    MongoDB具体操作方法(数据库、集合、文档的CRUD操作)

    MongoDB具体操作方法 包括数据库、集合、文档的CRUD操作 基础操作文档 文档还包含MongoDB的Windows和Linux安装教程 和关于MongoDB的内容以及ObjectID介绍

    redis和mongodb数据库操作方法

    NoSQL是一项全新的数据库革命性运动,虽然它的历史可以追溯到1998年,但是NoSQL真正深⼊⼼并得到⼴泛的应⽤是在进⼊⼤数据时候以后,业界普遍认为NoSQL是更适合大数据存储的技术方案,这才使得NoSQL的发展达到了...

    MongoDB基本操作指南

    针对MongoDB的操作都使用JSON风格语法,客户端提交或接收的数据都使用JSON形式来展现。相对于SQL来说,更加直观,容易理解和掌握。Schema-less,支持嵌入子文档:MongoDB是一个Schema-free的文档数据库。一个数据库...

    MongoDB数据库基本操作方法

    本资源旨在为开发者提供全面、系统的MongoDB操作指南,帮助他们在数据处理的道路上更加得心应手。无论你是初学者还是经验丰富的开发者,都能在本资源中找到你所需的知识和技能,为你的项目注入强大的数据动力。 ...

    spring-data使用mongodbTemplate对MongoDB进行读写操作

    spring data mongodb的demo程序,参考App.java中的调用方法,mongodb配置文件在resources目录下,整个项目使用maven,适合初学者学习。

    MongoDB数据库操作和面试专题及答案.zip

    3. **索引与性能优化**:掌握MongoDB的索引原理和使用方法,了解如何通过索引提升查询性能。 4. **聚合框架**:学习MongoDB的聚合框架,掌握如何进行复杂的数据聚合和分析操作。 5. **数据建模**:了解MongoDB的...

    python连接、操作mongodb数据库的方法实例详解

    主要介绍了python连接、操作mongodb数据库的方法,结合实例形式详细分析了Python针对MongoDB数据库的连接、查询、排序等相关操作技巧,需要的朋友可以参考下

    MongoDB数据库文档操作方法(必看篇)

    前面的话 本文将详细介绍MongoDB数据库关于文档的增删改查 如果数据库中不存在集合,则MongoDB将创建此集合,然后将文档插入到该集合中 ...也就是说save()方法和insert()方法的区别是,save()方法可以复写或修改,而in

    Sprint Boot 集成MongoDB的操作方法

    最近接手一个Springboot项目,需要在原项目上增加一些需求,用到了mongodb。下面通过本文给大家分享Sprint Boot 集成MongoDB的操作方法,需要的朋友参考下吧

    mongodb的安装已经操作方法和一些规则

    mongodb的安装已经操作方法和一些规则,关于其使用的一些方法和优化之类的。

    mongodb 数据库基本操作.docx

    mongodb 数据库基本操作 MongoDB 是一个流行的 NoSQL 文档型数据库,它...在 MongoDB 中,你可以使用 insertOne、insertMany 或 save 方法来插入文档。 javascript db.mycollection.insertOne({ name: "Alice", age

    java操作mongodb的工具类

    java操作mongodb的工具类,增删查改方法

    PHP操作MONGODB详细文档

    PHP操作MONGODB详细文档,详细介绍php操作mongod的方法

    2020年最新MongoDB 4.0专讲从入门到精通视频教程.txt

    day3:MongoDB增删改查操作实践 day4:教你学会MongoDB聚合操作 day5:索引的特性及应用 day6:MongoDB实例搭建仓位管理API day7:数据模型优化及设计 day8:复制集介绍及演练 day9:海量数据分片 day10:数据库认证与授权...

    mongodb 数据库基本操作.doc

    mongodb 数据库基本操作 MongoDB数据库的基本操作涉及多个方面,包括连接数据库、创建数据库、插入数据、查询数据、更新数据和删除数据等。以下是一些基本操作的简要说明: 连接MongoDB数据库: 使用MongoDB的...

    tp5(thinkPHP5)操作mongoDB数据库的方法

    主要介绍了tp5(thinkPHP5)操作mongoDB数据库的方法,结合实例形式简单分析了mongoDB数据库及thinkPHP5连接、查询MongoDB数据库的基本操作技巧,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics