java操作MongoDB工具類分享


 
  1. .limit(mongoDBCursor.getLimit());

  2. }

  3. if (mongoDBCursor.getSortObject() != null) {

  4. cursorToUse = cursorToUse.sort(mongoDBCursor.getSortObject());

  5. }

  6. return cursorToUse;

  7. }

  8. };

  9. return find(mongoDBCursor, dbObject, cursorPreparer,customField);

  10. }

  11.  
  12. /**

  13. * 查詢(私有方法,真正的查詢操作)

  14. *

  15. * @param query 查詢條件

  16. * @param mongoDBCursor 查詢實體

  17. * @param cursorPreparer 查詢轉換接口

  18. */

  19. private static List<DBObject> find(MongoDBCursor mongoDBCursor, DBObject query, MongoDBCursorPreparer cursorPreparer,BasicDBObjectBuilder customField) {

  20. DBCursor dbCursor = null;

  21. if(customField == null) {

  22. dbCursor = MongoDBCommonUtil.getCollection(mongoDBCursor).find(query);

  23. } else {

  24. dbCursor = MongoDBCommonUtil.getCollection(mongoDBCursor).find(query,customField.get());

  25. }

  26. if (cursorPreparer != null) {

  27. dbCursor = cursorPreparer.prepare(dbCursor);

  28. }

  29. return dbCursor.toArray();

  30. }

  31.  
  32. /**

  33. * Count查詢

  34. *

  35. * @param mongoDBCursor 查詢實體

  36. * @return 總數

  37. */

  38. public static long count(MongoDBCursor mongoDBCursor) {

  39. DBObject dbObject = getMapped(mongoDBCursor.getFieldMap());

  40. return MongoDBCommonUtil.getCollection(mongoDBCursor).count(dbObject);

  41.  
  42. }

  43.  
  44. /**

  45. * 把參數Map轉換DBObject

  46. *

  47. * @param map 查詢條件

  48. * @return DBObject

  49. */

  50. private static DBObject getMapped(Map<String, Object> map) {

  51. DBObject dbObject = new BasicDBObject();

  52. Iterator<Map.Entry<String, Object>> iterable = map.entrySet().iterator();

  53. while (iterable.hasNext()) {

  54. Map.Entry<String, Object> entry = iterable.next();

  55. Object value = entry.getValue();

  56. String key = entry.getKey();

  57. if (key.startsWith("$") && value instanceof Map) {

  58. BasicBSONList basicBSONList = new BasicBSONList();

  59. Map<String, Object> conditionsMap = ((Map) value);

  60. // Set<String> keys = conditionsMap.keySet();

  61. for (String k : conditionsMap.keySet()) {

  62. Object conditionsValue = conditionsMap.get(k);

  63. if (conditionsValue instanceof Collection) {

  64. conditionsValue = convertArray(conditionsValue);

  65. }

  66. DBObject dbObject2 = new BasicDBObject(k, conditionsValue);

  67. basicBSONList.add(dbObject2);

  68. }

  69. value = basicBSONList;

  70. } else if (value instanceof Collection) {

  71. value = convertArray(value);

  72. } else if (!key.startsWith("$") && value instanceof Map) {

  73. value = getMapped(((Map) value));

  74. }

  75. dbObject.put(key, value);

  76. }

  77. return dbObject;

  78. }

  79.  
  80. /**

  81. * 轉換成Object[]

  82. *

  83. * @param value 待轉換實體

  84. * @return Object[]

  85. */

  86. private static Object[] convertArray(Object value) {

  87. Object[] values = ((Collection) value).toArray();

  88. return values;

  89. }

  90.  
  91. /**

  92. * 添加操作

  93. *

  94. * @param mongoDBEntity 實體

  95. */

  96. public static void add(MongoDBEntity mongoDBEntity) {

  97. DBObject dbObject = new BasicDBObject(mongoDBEntity.getFieldMap());

  98. MongoDBCommonUtil.getCollection(mongoDBEntity).insert(dbObject);

  99. }

  100.  
  101. /**

  102. * 批量處理添加操作

  103. *

  104. * @param list 批量字段數據

  105. * @param mongoDBEntity 實體

  106. */

  107. public static void add(MongoDBEntity mongoDBEntity, List<Map<String, Object>> list) {

  108. for (Map<String, Object> map : list) {

  109. mongoDBEntity.setFieldMap(map);

  110. add(mongoDBEntity);

  111. }

  112. }

  113.  
  114. /**

  115. * 刪除操作

  116. *

  117. * @param mongoDBEntity 實體

  118. */

  119. public static void delete(MongoDBEntity mongoDBEntity) {

  120. DBObject dbObject = new BasicDBObject(mongoDBEntity.getFieldMap());

  121. MongoDBCommonUtil.getCollection(mongoDBEntity).remove(dbObject);

  122. }

  123.  
  124. /**

  125. * 刪除操作,根據主鍵

  126. *

  127. * @param id 主鍵

  128. * @param mongoDBEntity 實體

  129. */

  130. public static void delete(MongoDBEntity mongoDBEntity, String id) {

  131. Map<String, Object> map = new HashMap<String, Object>();

  132. map.put("_id", new ObjectId(id));

  133. mongoDBEntity.setFieldMap(map);

  134. delete(mongoDBEntity);

  135. }

  136.  
  137. /**

  138. * 刪除全部

  139. *

  140. * @param mongoDBEntity 實體

  141. */

  142. public static void deleteAll(MongoDBEntity mongoDBEntity) {

  143. MongoDBCommonUtil.getCollection(mongoDBEntity).drop();

  144. }

  145.  
  146. /**

  147. * 修改操作

  148. * 會用一個新文檔替換現有文檔,文檔key結構會發生改變

  149. * 比如原文檔{"_id":"123","name":"zhangsan","age":12}當根據_id修改age

  150. * value爲{"age":12}新建的文檔name值會沒有,結構發生了改變

  151. *

  152. * @param mongoDBUpdate 更新實體

  153. */

  154. public static void update(MongoDBUpdate mongoDBUpdate) {

  155. executeUpdate(mongoDBUpdate, new UpdateCallback() {

  156. public DBObject doCallback(DBObject valueDBObject) {

  157. return valueDBObject;

  158. }

  159. });

  160. }

  161.  
  162. /**

  163. * 修改操作,使用$set修改器

  164. * 用來指定一個鍵值,如果鍵不存在,則自動創建,會更新原來文檔, 不會生成新的, 結構不會發生改變

  165. *

  166. * @param mongoDBUpdate 更新實體

  167. */

  168. public static void updateSet(MongoDBUpdate mongoDBUpdate) {

  169. executeUpdate(mongoDBUpdate, new UpdateCallback() {

  170. public DBObject doCallback(DBObject valueDBObject) {

  171. return new BasicDBObject("$set", valueDBObject);

  172. }

  173. });

  174. }

  175.  
  176. /**

  177. * 修改操作,使用$inc修改器

  178. * 修改器鍵的值必須爲數字

  179. * 如果鍵存在增加或減少鍵的值, 如果不存在創建鍵

  180. *

  181. * @param mongoDBUpdate 更新實體

  182. */

  183. public static void updateInc(MongoDBUpdate mongoDBUpdate) {

  184. executeUpdate(mongoDBUpdate, new UpdateCallback() {

  185. public DBObject doCallback(DBObject valueDBObject) {

  186. return new BasicDBObject("$inc", valueDBObject);

  187. }

  188. });

  189. }

  190.  
  191. /**

  192. * 修改(私有方法)

  193. *

  194. * @param mongoDBUpdate 更新實體

  195. * @param updateCallback 更新回調

  196. */

  197. private static void executeUpdate(MongoDBUpdate mongoDBUpdate, UpdateCallback updateCallback) {

  198. DBObject whereDBObject = new BasicDBObject(mongoDBUpdate.getWhereMap());

  199. DBObject valueDBObject = new BasicDBObject(mongoDBUpdate.getValueMap());

  200. valueDBObject = updateCallback.doCallback(valueDBObject);

  201. MongoDBCommonUtil.getCollection(mongoDBUpdate).update(whereDBObject, valueDBObject);

  202. }

  203.  
  204.  
  205. public static void main(String[] args) {

  206. try {

  207. //獲取操作DB

  208. DB db = MongoDBCommonUtil.getDB("192.168.227.170", 20011,"lagd","lagd_rw","lagd_pwd");

  209. MongoDBCursor mongoDBCursor = new MongoDBCursor();

  210. mongoDBCursor.setDb(db); //賦值DB

  211. mongoDBCursor.setCollectionName("lagd_data_dictionary"); //賦值集合名

  212. //封裝查詢條件

  213. Map<String, Object> fieldMap = new HashMap<String, Object>();

  214. fieldMap.put("type","dataSource");

  215. mongoDBCursor.setFieldMap(fieldMap);

  216. //賦值skip

  217. mongoDBCursor.setSkip(1);

  218. //賦值limit

  219. mongoDBCursor.setLimit(1);

  220. //封裝Sort

  221. Map<String, Object> sortMap = new LinkedHashMap<String, Object>();

  222. sortMap.put("key",1);

  223. mongoDBCursor.setSort(sortMap);

  224. //自定義查詢字段

  225. Map<String, Object> customFieldMap = new LinkedHashMap<String, Object>();

  226. customFieldMap.put("type","1");

  227. customFieldMap.put("key","1");

  228. customFieldMap.put("value","1");

  229. mongoDBCursor.setCustomFieldMap(customFieldMap);

  230. //查詢

  231. List<DBObject> result = MongoDBUtil.find(mongoDBCursor);

  232. for(DBObject dbObject : result){

  233. for(String key : dbObject.keySet()){

  234. System.out.println("鍵:" + key + "; 值:" + dbObject.get(key));

  235. }

  236. }

  237. } catch (Exception e) {

  238. e.printStackTrace();

  239. }

  240. }

  241. }

 MongoDBCursorPreparer


 
  1. import com.mongodb.DBCursor;

  2.  
  3. /**

  4. * 查詢轉換接口定義

  5. *

  6. * @author: alex

  7. * @time: 14-1-21 下午4:55

  8. * @version: 1.0

  9. */

  10. public interface MongoDBCursorPreparer {

  11.  
  12. DBCursor prepare(DBCursor cursor);

  13. }

 UpdateCallback


 
  1. import com.mongodb.DBObject;

  2.  
  3. /**

  4. * MongoDB更新操作接口定義

  5. *

  6. * @author: alex

  7. * @time: 14-1-21 下午5:25

  8. * @version: 1.0

  9. */

  10. interface UpdateCallback {

  11.  
  12. DBObject doCallback(DBObject valueDBObject);

  13. }

 

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