mongodb- Java API 查询操作

[java]  view plain copy print ?
  1. package com.x.mongodb;  
  2.   
  3. import java.net.UnknownHostException;  
  4. import java.util.Collection;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.Map;  
  8. import java.util.Map.Entry;  
  9. import java.util.Set;  
  10.   
  11. import org.bson.types.BasicBSONList;  
  12. import org.bson.types.ObjectId;  
  13.   
  14. import com.mongodb.BasicDBObject;  
  15. import com.mongodb.DB;  
  16. import com.mongodb.DBCollection;  
  17. import com.mongodb.DBCursor;  
  18. import com.mongodb.DBObject;  
  19. import com.mongodb.Mongo;  
  20. import com.mongodb.MongoException;  
  21.   
  22. /** 
  23.  * 查询</br> 
  24.  *  : $in   { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}</br> 
  25.  *  : $nin  { "age" : { "$nin" : [ 1 , 2]}} 
  26.  *  : $or   { "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}]}</br> 
  27.  *  : $or and{ "$or" : [ { "name1" : { "$in" : [ "zhou28-1" , "zhou29"]}}] , "name2" : "zhou"}</br> 
  28.  *  : 范围查询 { "age" : { "$gte" : 2 , "$lte" : 21}}</br> 
  29.  *  : $ne   { "age" : { "$ne" : 23}}</br> 
  30.  *  : $lt   { "age" : { "$lt" : 23}} 
  31.  * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a> 
  32.  * @version <b>1.0</b> 
  33.  */  
  34. public final class MongoDBUtil {  
  35.   
  36.     private static final String HOST = "127.0.0.1";  
  37.   
  38.     private static final String dbName = "test";  
  39.   
  40.     private static Mongo mongo;  
  41.   
  42.     private static DB db;  
  43.   
  44.     static {  
  45.         try {  
  46.             mongo = new Mongo(HOST);  
  47.             db = mongo.getDB(dbName);  
  48.             // db.authenticate(username, passwd)  
  49.         } catch (UnknownHostException e) {  
  50.             e.printStackTrace();  
  51.         } catch (MongoException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.     }  
  55.   
  56.     private MongoDBUtil() {  
  57.     }  
  58.       
  59.     /** 
  60.      * 判断集合是否存在 
  61.      * <br>------------------------------<br> 
  62.      * @param collectionName 
  63.      * @return 
  64.      */  
  65.     public static boolean collectionExists(String collectionName) {  
  66.         return db.collectionExists(collectionName);  
  67.     }  
  68.       
  69.     /** 
  70.      * 查询单个,按主键查询  
  71.      * <br>------------------------------<br> 
  72.      * @param id   
  73.      * @param collectionName 
  74.      */  
  75.     public static void findById(String id, String collectionName) {  
  76.         Map<String, Object> map = new HashMap<String, Object>();  
  77.         map.put("_id"new ObjectId(id));  
  78.         findOne(map, collectionName);  
  79.     }  
  80.       
  81.     /** 
  82.      * 查询单个 
  83.      * <br>------------------------------<br> 
  84.      * @param map 
  85.      * @param collectionName 
  86.      */  
  87.     public static void findOne(Map<String, Object> map, String collectionName) {  
  88.         DBObject dbObject = getMapped(map);  
  89.         DBObject object = getCollection(collectionName).findOne(dbObject);  
  90.         print(object);  
  91.     }  
  92.       
  93.     /** 
  94.      * 查询全部 
  95.      * <br>------------------------------<br> 
  96.      * @param cursor 
  97.      * @param collectionName 
  98.      */  
  99.     public static void findAll(CursorObject cursor, String collectionName) {  
  100.         find(new HashMap<String, Object>(), cursor,  collectionName);  
  101.     }  
  102.       
  103.     /** 
  104.      * count 
  105.      * <br>------------------------------<br> 
  106.      * @param map 
  107.      * @param collectionName 
  108.      * @return 
  109.      */  
  110.     public static long count(Map<String, Object> map, String collectionName) {  
  111.         DBObject dbObject = getMapped(map);  
  112.         return getCollection(collectionName).count(dbObject);  
  113.           
  114.     }  
  115.       
  116.     /** 
  117.      * 按条件查询 </br> 
  118.      * 支持skip,limit,sort 
  119.      * <br>------------------------------<br> 
  120.      * @param map 
  121.      * @param cursor 
  122.      * @param collectionName 
  123.      */  
  124.     public static void find(Map<String, Object> map, CursorObject cursor, String collectionName) {  
  125.         DBObject dbObject = getMapped(map);  
  126.         find(dbObject, cursor, collectionName);  
  127.     }  
  128.       
  129.     /** 
  130.      * 查询 
  131.      * <br>------------------------------<br> 
  132.      * @param dbObject 
  133.      * @param cursor 
  134.      * @param collectionName 
  135.      */  
  136.     public static void find(DBObject dbObject, final CursorObject cursor,  String collectionName) {  
  137.         CursorPreparer cursorPreparer  = cursor == null ? null : new CursorPreparer() {  
  138.             public DBCursor prepare(DBCursor dbCursor) {  
  139.                 if (cursor == null) {  
  140.                     return dbCursor;  
  141.                 }  
  142.                 if (cursor.getLimit() <= 0 && cursor.getSkip() <=0 && cursor.getSortObject() == null) {  
  143.                     return dbCursor;  
  144.                 }  
  145.                 DBCursor cursorToUse = dbCursor;  
  146.                 if (cursor.getSkip() > 0) {  
  147.                     cursorToUse = cursorToUse.skip(cursor.getSkip());  
  148.                 }  
  149.                 if (cursor.getLimit() > 0) {  
  150.                     cursorToUse = cursorToUse.limit(cursor.getLimit());  
  151.                 }  
  152.                 if (cursor.getSortObject() != null) {  
  153.                     cursorToUse = cursorToUse.sort(cursor.getSortObject());  
  154.                 }  
  155.                 return cursorToUse;  
  156.             }  
  157.         };  
  158.         find(dbObject, cursor, cursorPreparer, collectionName);  
  159.     }  
  160.       
  161.     /** 
  162.      * 查询 
  163.      * <br>------------------------------<br> 
  164.      * @param dbObject 
  165.      * @param cursor 
  166.      * @param cursorPreparer 
  167.      * @param collectionName 
  168.      */  
  169.     public static void find(DBObject dbObject, CursorObject cursor, CursorPreparer cursorPreparer, String collectionName) {  
  170.         DBCursor dbCursor = getCollection(collectionName).find(dbObject);  
  171.         if (cursorPreparer != null) {  
  172.             dbCursor = cursorPreparer.prepare(dbCursor);  
  173.         }  
  174.         Iterator<DBObject> iterator = dbCursor.iterator();  
  175.         while (iterator.hasNext()) {  
  176.             print(iterator.next());  
  177.         }  
  178.     }  
  179.       
  180.     /** 
  181.      * 获取集合(表) 
  182.      * <br>------------------------------<br> 
  183.      * @param collectionName 
  184.      * @return 
  185.      */  
  186.     public static DBCollection getCollection(String collectionName) {  
  187.         return db.getCollection(collectionName);  
  188.     }  
  189.       
  190.     /** 
  191.      * 获取所有集合名称 
  192.      * <br>------------------------------<br> 
  193.      * @return 
  194.      */  
  195.     public static Set<String> getCollection() {  
  196.         return db.getCollectionNames();  
  197.     }  
  198.       
  199.     /** 
  200.      * 创建集合 
  201.      * <br>------------------------------<br> 
  202.      * @param collectionName 
  203.      * @param options 
  204.      */  
  205.     public static void createCollection(String collectionName, DBObject options) {  
  206.         db.createCollection(collectionName, options);  
  207.     }  
  208.       
  209.     /** 
  210.      * 删除 
  211.      * <br>------------------------------<br> 
  212.      * @param collectionName 
  213.      */  
  214.     public static void dropCollection(String collectionName) {  
  215.         DBCollection collection = getCollection(collectionName);  
  216.         collection.drop();  
  217.     }  
  218.       
  219.     /** 
  220.      *  
  221.      * <br>------------------------------<br> 
  222.      * @param map 
  223.      * @return 
  224.      */  
  225.     private static DBObject getMapped(Map<String, Object> map) {  
  226.         DBObject dbObject = new BasicDBObject();  
  227.         Iterator<Entry<String, Object>> iterable = map.entrySet().iterator();  
  228.         while (iterable.hasNext()) {  
  229.             Entry<String, Object> entry = iterable.next();  
  230.             Object value = entry.getValue();  
  231.             String key = entry.getKey();  
  232.             if (key.startsWith("$") && value instanceof Map) {  
  233.                 BasicBSONList basicBSONList = new BasicBSONList();  
  234.                 Map<String, Object> conditionsMap = ((Map)value);  
  235.                 Set<String> keys = conditionsMap.keySet();  
  236.                 for (String k : keys) {  
  237.                     Object conditionsValue = conditionsMap.get(k);  
  238.                     if (conditionsValue instanceof Collection) {  
  239.                         conditionsValue =  convertArray(conditionsValue);  
  240.                     }  
  241.                     DBObject dbObject2 = new BasicDBObject(k, conditionsValue);  
  242.                     basicBSONList.add(dbObject2);  
  243.                 }  
  244.                 value  = basicBSONList;  
  245.             } else if (value instanceof Collection) {  
  246.                 value =  convertArray(value);  
  247.             } else if (!key.startsWith("$") && value instanceof Map) {  
  248.                 value = getMapped(((Map)value));  
  249.             }  
  250.             dbObject.put(key, value);  
  251.         }  
  252.         return dbObject;  
  253.     }  
  254.       
  255.     private static Object[] convertArray(Object value) {  
  256.         Object[] values = ((Collection)value).toArray();  
  257.         return values;  
  258.     }  
  259.       
  260.     private static void print(DBObject object) {  
  261.         Set<String> keySet = object.keySet();  
  262.         for (String key : keySet) {  
  263.             print(object.get(key));  
  264.         }  
  265.     }  
  266.       
  267.     private static void print(Object object) {  
  268.         System.out.println(object.toString());  
  269.     }  
  270. }  
[java]  view plain copy print ?
  1. package com.x.mongodb;  
  2.   
  3. /** 
  4.  * 排序规则 
  5.  * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a> 
  6.  * @version <b>1.0</b> 
  7.  */  
  8. public enum Order {  
  9.       
  10.     ASC, DESC  
  11. }  
[java]  view plain copy print ?
  1. package com.x.mongodb;  
  2.   
  3. import java.util.LinkedHashMap;  
  4. import java.util.Map;  
  5.   
  6. import com.mongodb.BasicDBObject;  
  7. import com.mongodb.DBObject;  
  8.   
  9. /** 
  10.  * 排序对象 
  11.  * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a> 
  12.  * @version <b>1.0</b> 
  13.  */  
  14. public class Sort {  
  15.   
  16.     /** key为排序的名称, value为顺序 */  
  17.     private Map<String, Order> field = new LinkedHashMap<String, Order>();  
  18.   
  19.     public Sort() {  
  20.     }  
  21.   
  22.     public Sort(String key, Order order) {  
  23.         field.put(key, order);  
  24.     }  
  25.   
  26.     public Sort on(String key, Order order) {  
  27.         field.put(key, order);  
  28.         return this;  
  29.     }  
  30.   
  31.     public DBObject getSortObject() {  
  32.         DBObject dbo = new BasicDBObject();  
  33.         for (String k : field.keySet()) {  
  34.             dbo.put(k, (field.get(k).equals(Order.ASC) ? 1 : -1));  
  35.         }  
  36.         return dbo;  
  37.     }  
  38. }  
[java]  view plain copy print ?
  1. package com.x.mongodb;  
  2.   
  3. import com.mongodb.DBCursor;  
  4.   
  5.   
  6. /** 
  7.  * 分页,排序处理 
  8.  * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a> 
  9.  * @version <b>1.0</b> 
  10.  */  
  11. public interface CursorPreparer {  
  12.   
  13.     DBCursor prepare(DBCursor cursor);  
  14. }  
[java]  view plain copy print ?
  1. package com.x.mongodb;  
  2.   
  3. import com.mongodb.DBObject;  
  4.   
  5. /** 
  6.  * 分页,排序对象 
  7.  * @author <a href="http://blog.csdn.net/java2000_wl">java2000_wl</a> 
  8.  * @version <b>1.0</b> 
  9.  */  
  10. public class CursorObject {  
  11.   
  12.     private int skip;  
  13.       
  14.     private int limit;  
  15.       
  16.     private Sort sort;  
  17.       
  18.     public CursorObject skip(int skip) {  
  19.         this.skip = skip;  
  20.         return this;  
  21.     }  
  22.   
  23.     public CursorObject limit(int limit) {  
  24.         this.limit = limit;  
  25.         return this;  
  26.     }  
  27.       
  28.     public int getSkip() {  
  29.         return skip;  
  30.     }  
  31.   
  32.     public int getLimit() {  
  33.         return limit;  
  34.     }  
  35.   
  36.     public Sort sort() {  
  37.         if (this.sort == null) {  
  38.             this.sort = new Sort();  
  39.         }  
  40.         return this.sort;  
  41.     }  
  42.       
  43.     public DBObject getSortObject() {  
  44.         if (this.sort == null) {  
  45.             return null;  
  46.         }  
  47.         return this.sort.getSortObject();  
  48.     }  
  49. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值