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. }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值