mongodb- Java API 查詢操作

package com.x.mongodb;

import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.bson.types.BasicBSONList;
import org.bson.types.ObjectId;

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.MongoException;

/**
 * 查詢</br>
 *  : $in	{ "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}</br>
 *  : $nin	{ "age" : { "$nin" : [ 1 , 2]}}
 *  : $or	{ "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}]}</br>
 *  : $or and{ "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}] , "name2" : "zhou"}</br>
 *  : 範圍查詢 { "age" : { "$gte" : 2 , "$lte" : 21}}</br>
 *  : $ne	{ "age" : { "$ne" : 23}}</br>
 *  : $lt 	{ "age" : { "$lt" : 23}}
 * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a>
 * @version <b>1.0</b>
 */
public final class MongoDBUtil {

	private static final String HOST = "127.0.0.1";

	private static final String dbName = "test";

	private static Mongo mongo;

	private static DB db;

	static {
		try {
			mongo = new Mongo(HOST);
			db = mongo.getDB(dbName);
			// db.authenticate(username, passwd)
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}

	private MongoDBUtil() {
	}
	
	/**
	 * 判斷集合是否存在
	 * <br>------------------------------<br>
	 * @param collectionName
	 * @return
	 */
	public static boolean collectionExists(String collectionName) {
		return db.collectionExists(collectionName);
	}
	
	/**
	 * 查詢單個,按主鍵查詢 
	 * <br>------------------------------<br>
	 * @param id  
	 * @param collectionName
	 */
	public static void findById(String id, String collectionName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("_id", new ObjectId(id));
		findOne(map, collectionName);
	}
	
	/**
	 * 查詢單個
	 * <br>------------------------------<br>
	 * @param map
	 * @param collectionName
	 */
	public static void findOne(Map<String, Object> map, String collectionName) {
		DBObject dbObject = getMapped(map);
		DBObject object = getCollection(collectionName).findOne(dbObject);
		print(object);
	}
	
	/**
	 * 查詢全部
	 * <br>------------------------------<br>
	 * @param cursor
	 * @param collectionName
	 */
	public static void findAll(CursorObject cursor, String collectionName) {
		find(new HashMap<String, Object>(), cursor,  collectionName);
	}
	
	/**
	 * count
	 * <br>------------------------------<br>
	 * @param map
	 * @param collectionName
	 * @return
	 */
	public static long count(Map<String, Object> map, String collectionName) {
		DBObject dbObject = getMapped(map);
		return getCollection(collectionName).count(dbObject);
		
	}
	
	/**
	 * 按條件查詢 </br>
	 * 支持skip,limit,sort
	 * <br>------------------------------<br>
	 * @param map
	 * @param cursor
	 * @param collectionName
	 */
	public static void find(Map<String, Object> map, CursorObject cursor, String collectionName) {
		DBObject dbObject = getMapped(map);
		find(dbObject, cursor, collectionName);
	}
	
	/**
	 * 查詢
	 * <br>------------------------------<br>
	 * @param dbObject
	 * @param cursor
	 * @param collectionName
	 */
	public static void find(DBObject dbObject, final CursorObject cursor,  String collectionName) {
		CursorPreparer cursorPreparer  = cursor == null ? null : new CursorPreparer() {
			public DBCursor prepare(DBCursor dbCursor) {
				if (cursor == null) {
					return dbCursor;
				}
				if (cursor.getLimit() <= 0 && cursor.getSkip() <=0 && cursor.getSortObject() == null) {
					return dbCursor;
				}
				DBCursor cursorToUse = dbCursor;
				if (cursor.getSkip() > 0) {
					cursorToUse = cursorToUse.skip(cursor.getSkip());
				}
				if (cursor.getLimit() > 0) {
					cursorToUse = cursorToUse.limit(cursor.getLimit());
				}
				if (cursor.getSortObject() != null) {
					cursorToUse = cursorToUse.sort(cursor.getSortObject());
				}
				return cursorToUse;
			}
		};
		find(dbObject, cursor, cursorPreparer, collectionName);
	}
	
	/**
	 * 查詢
	 * <br>------------------------------<br>
	 * @param dbObject
	 * @param cursor
	 * @param cursorPreparer
	 * @param collectionName
	 */
	public static void find(DBObject dbObject, CursorObject cursor, CursorPreparer cursorPreparer, String collectionName) {
		DBCursor dbCursor = getCollection(collectionName).find(dbObject);
		if (cursorPreparer != null) {
			dbCursor = cursorPreparer.prepare(dbCursor);
		}
		Iterator<DBObject> iterator = dbCursor.iterator();
		while (iterator.hasNext()) {
			print(iterator.next());
		}
	}
	
	/**
	 * 獲取集合(表)
	 * <br>------------------------------<br>
	 * @param collectionName
	 * @return
	 */
	public static DBCollection getCollection(String collectionName) {
		return db.getCollection(collectionName);
	}
	
	/**
	 * 獲取所有集合名稱
	 * <br>------------------------------<br>
	 * @return
	 */
	public static Set<String> getCollection() {
		return db.getCollectionNames();
	}
	
	/**
	 * 創建集合
	 * <br>------------------------------<br>
	 * @param collectionName
	 * @param options
	 */
	public static void createCollection(String collectionName, DBObject options) {
		db.createCollection(collectionName, options);
	}
	
	/**
	 * 刪除
	 * <br>------------------------------<br>
	 * @param collectionName
	 */
	public static void dropCollection(String collectionName) {
		DBCollection collection = getCollection(collectionName);
		collection.drop();
	}
	
	/**
	 * 
	 * <br>------------------------------<br>
	 * @param map
	 * @return
	 */
	private static DBObject getMapped(Map<String, Object> map) {
		DBObject dbObject = new BasicDBObject();
		Iterator<Entry<String, Object>> iterable = map.entrySet().iterator();
		while (iterable.hasNext()) {
			Entry<String, Object> entry = iterable.next();
			Object value = entry.getValue();
			String key = entry.getKey();
			if (key.startsWith("$") && value instanceof Map) {
				BasicBSONList basicBSONList = new BasicBSONList();
				Map<String, Object> conditionsMap = ((Map)value);
				Set<String> keys = conditionsMap.keySet();
				for (String k : keys) {
					Object conditionsValue = conditionsMap.get(k);
					if (conditionsValue instanceof Collection) {
						conditionsValue =  convertArray(conditionsValue);
					}
					DBObject dbObject2 = new BasicDBObject(k, conditionsValue);
					basicBSONList.add(dbObject2);
				}
				value  = basicBSONList;
			} else if (value instanceof Collection) {
				value =  convertArray(value);
			} else if (!key.startsWith("$") && value instanceof Map) {
				value = getMapped(((Map)value));
			}
			dbObject.put(key, value);
		}
		return dbObject;
	}
	
	private static Object[] convertArray(Object value) {
		Object[] values = ((Collection)value).toArray();
		return values;
	}
	
	private static void print(DBObject object) {
		Set<String> keySet = object.keySet();
		for (String key : keySet) {
			print(object.get(key));
		}
	}
	
	private static void print(Object object) {
		System.out.println(object.toString());
	}
}
package com.x.mongodb;

/**
 * 排序規則
 * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a>
 * @version <b>1.0</b>
 */
public enum Order {
	
	ASC, DESC
}
package com.x.mongodb;

import java.util.LinkedHashMap;
import java.util.Map;

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

/**
 * 排序對象
 * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a>
 * @version <b>1.0</b>
 */
public class Sort {

	/** key爲排序的名稱, value爲順序 */
	private Map<String, Order> field = new LinkedHashMap<String, Order>();

	public Sort() {
	}

	public Sort(String key, Order order) {
		field.put(key, order);
	}

	public Sort on(String key, Order order) {
		field.put(key, order);
		return this;
	}

	public DBObject getSortObject() {
		DBObject dbo = new BasicDBObject();
		for (String k : field.keySet()) {
			dbo.put(k, (field.get(k).equals(Order.ASC) ? 1 : -1));
		}
		return dbo;
	}
}
package com.x.mongodb;

import com.mongodb.DBCursor;


/**
 * 分頁,排序處理
 * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a>
 * @version <b>1.0</b>
 */
public interface CursorPreparer {

	DBCursor prepare(DBCursor cursor);
}
package com.x.mongodb;

import com.mongodb.DBObject;

/**
 * 分頁,排序對象
 * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a>
 * @version <b>1.0</b>
 */
public class CursorObject {

	private int skip;
	
	private int limit;
	
	private Sort sort;
	
	public CursorObject skip(int skip) {
		this.skip = skip;
		return this;
	}

	public CursorObject limit(int limit) {
		this.limit = limit;
		return this;
	}
	
	public int getSkip() {
		return skip;
	}

	public int getLimit() {
		return limit;
	}

	public Sort sort() {
		if (this.sort == null) {
			this.sort = new Sort();
		}
		return this.sort;
	}
	
	public DBObject getSortObject() {
		if (this.sort == null) {
			return null;
		}
		return this.sort.getSortObject();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章