设为首页 收藏本站
查看: 1112|回复: 0

[经验分享] mongodb- Java API 查询操作

[复制链接]

尚未签到

发表于 2015-7-8 11:25:11 | 显示全部楼层 |阅读模式
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;
/**
* 查询
*  : $in{ "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}
*  : $nin{ "age" : { "$nin" : [ 1 , 2]}}
*  : $or{ "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}]}
*  : $or and{ "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}] , "name2" : "zhou"}
*  : 范围查询 { "age" : { "$gte" : 2 , "$lte" : 21}}
*  : $ne{ "age" : { "$ne" : 23}}
*  : $lt { "age" : { "$lt" : 23}}
* @author java2000_wl
* @version 1.0
*/
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() {
}
/**
* 判断集合是否存在
* ------------------------------
* @param collectionName
* @return
*/
public static boolean collectionExists(String collectionName) {
return db.collectionExists(collectionName);
}
/**
* 查询单个,按主键查询
* ------------------------------
* @param id  
* @param collectionName
*/
public static void findById(String id, String collectionName) {
Map map = new HashMap();
map.put("_id", new ObjectId(id));
findOne(map, collectionName);
}
/**
* 查询单个
* ------------------------------
* @param map
* @param collectionName
*/
public static void findOne(Map map, String collectionName) {
DBObject dbObject = getMapped(map);
DBObject object = getCollection(collectionName).findOne(dbObject);
print(object);
}
/**
* 查询全部
* ------------------------------
* @param cursor
* @param collectionName
*/
public static void findAll(CursorObject cursor, String collectionName) {
find(new HashMap(), cursor,  collectionName);
}
/**
* count
* ------------------------------
* @param map
* @param collectionName
* @return
*/
public static long count(Map map, String collectionName) {
DBObject dbObject = getMapped(map);
return getCollection(collectionName).count(dbObject);
}
/**
* 按条件查询
* 支持skip,limit,sort
* ------------------------------
* @param map
* @param cursor
* @param collectionName
*/
public static void find(Map map, CursorObject cursor, String collectionName) {
DBObject dbObject = getMapped(map);
find(dbObject, cursor, collectionName);
}
/**
* 查询
* ------------------------------
* @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) {
cursorToUse = cursorToUse.limit(cursor.getLimit());
}
if (cursor.getSortObject() != null) {
cursorToUse = cursorToUse.sort(cursor.getSortObject());
}
return cursorToUse;
}
};
find(dbObject, cursor, cursorPreparer, collectionName);
}
/**
* 查询
* ------------------------------
* @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 iterator = dbCursor.iterator();
while (iterator.hasNext()) {
print(iterator.next());
}
}
/**
* 获取集合(表)
* ------------------------------
* @param collectionName
* @return
*/
public static DBCollection getCollection(String collectionName) {
return db.getCollection(collectionName);
}
/**
* 获取所有集合名称
* ------------------------------
* @return
*/
public static Set getCollection() {
return db.getCollectionNames();
}
/**
* 创建集合
* ------------------------------
* @param collectionName
* @param options
*/
public static void createCollection(String collectionName, DBObject options) {
db.createCollection(collectionName, options);
}
/**
* 删除
* ------------------------------
* @param collectionName
*/
public static void dropCollection(String collectionName) {
DBCollection collection = getCollection(collectionName);
collection.drop();
}
/**
*
* ------------------------------
* @param map
* @return
*/
private static DBObject getMapped(Map map) {
DBObject dbObject = new BasicDBObject();
Iterator iterable = map.entrySet().iterator();
while (iterable.hasNext()) {
Entry entry = iterable.next();
Object value = entry.getValue();
String key = entry.getKey();
if (key.startsWith("$") && value instanceof Map) {
BasicBSONList basicBSONList = new BasicBSONList();
Map conditionsMap = ((Map)value);
Set 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 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 java2000_wl
* @version 1.0
*/
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 java2000_wl
* @version 1.0
*/
public class Sort {
/** key为排序的名称, value为顺序 */
private Map field = new LinkedHashMap();
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 java2000_wl
* @version 1.0
*/
public interface CursorPreparer {
DBCursor prepare(DBCursor cursor);
}package com.x.mongodb;
import com.mongodb.DBObject;
/**
* 分页,排序对象
* @author java2000_wl
* @version 1.0
*/
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();
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84447-1-1.html 上篇帖子: Mongodb定时备份脚本和清除脚本 下篇帖子: 百度BAE 平台PHP对Mongodb的连接
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表