AND、OR和IN操作

  1. AND:
  2. public void testAnd(){
  3. //agender='female' AND age > 27
  4. DBObject queryCondition = new BasicDBObject();
  5. queryCondition.put("agender", "female");
  6. queryCondition.put("age", new BasicDBObject("$gt", 27));
  7. DBCursor dbCursor = coll.find(queryCondition);
  8. assertEquals(1, dbCursor.size());
  9. assertEquals("Jane", dbCursor.next().get("username"));
  10. }
  11. OR:
  12. public void testOrSingleField(){
  13. DBObject queryCondition = new BasicDBObject();
  14. //age<15 OR age>27
  15. queryCondition = new BasicDBObject();
  16. BasicDBList values = new BasicDBList();
  17. values.add(new BasicDBObject("age", new BasicDBObject("$gt", 27)));
  18. values.add(new BasicDBObject("age", new BasicDBObject("$lt", 15)));
  19. queryCondition.put("$or", values);
  20. DBCursor dbCursor = coll.find(queryCondition);
  21. assertEquals(3, dbCursor.size());
  22. assertEquals("tom", dbCursor.next().get("username"));
  23. }
  24. OR:
  25. public void testOrMultiFields(){
  26. DBObject queryCondition = new BasicDBObject();
  27. //agender=female OR age<=23
  28. queryCondition = new BasicDBObject();
  29. BasicDBList values = new BasicDBList();
  30. values.add(new BasicDBObject("agender", "female"));
  31. values.add(new BasicDBObject("age", new BasicDBObject("$lte", 23)));
  32. queryCondition.put("$or", values);
  33. DBCursor dbCursor = coll.find(queryCondition);
  34. assertEquals(4, dbCursor.size());
  35. assertEquals("Jim", dbCursor.next().get("username"));
  36. }
  37. IN:
  38. public void testIn(){
  39. DBObject queryCondition = new BasicDBObject();
  40. //age in [13, 47]
  41. queryCondition = new BasicDBObject();
  42. BasicDBList values = new BasicDBList();
  43. values.add(13);
  44. values.add(47);
  45. queryCondition.put("age", new BasicDBObject("$in", values));
  46. DBCursor dbCursor = coll.find(queryCondition);
  47. assertEquals(2, dbCursor.size());
  48. assertEquals("tom", dbCursor.next().get("username"));
  49. }

JAVA mongodb 聚合几种查询方式详解

  1. https://www.jb51.net/article/137196.htm
  2. 一、BasicDBObject
  3. 整个聚合查询是统计用户的各种状态下的用户数量为场景:
  4. 1.筛选条件:
  5. date为查询日期:
  6. BasicDBObject Query = new BasicDBObject();
  7. Query.put("time",new BasicDBObject("$gte", date + " 00:00:00")
  8. .append("$lte", date + " 23:59:59"));
  9. 如果有多个条件:直接加Query.put("status", 0);
  10. 如果有OR筛选:
  11. BasicDBList values = new BasicDBList();
  12. values.add(new BasicDBObject("status", new BasicDBObject("$exists",false)));
  13. values.add(new BasicDBObject("status", 0));
  14. Query.put("$or", values);
  15. 其中 new BasicDBObject("$exists",false)) 就是“status”不存在(mongodb文档可不等于实体的字段)
  16. 2.拼接match
  17. DBObject Match = new BasicDBObject("$match", Query);
  18. 将上一步的Query放入macth筛选中
  19. 3.拼接分组条件
  20. 此步相当于SQLGroup By
  21. BasicDBObject GroupBy = new BasicDBObject();// 分组条件
  22. GroupBy.put("userId", "$userId");//根据用户ID来分组
  23. 同第一步的筛选一样,如果有多个分组可直接添加在后面:GroupBy.put("status", "$status");
  24. 4.分组后查询
  25. 首先把分组拼接上:
  26. DBObject Select = new BasicDBObject("_id", GroupBy);
  27. 如果我们要对分组后的数据进行操作:(这里是用户的统计数量)
  28. Select.put("count", new BasicDBObject("$sum", 1));
  29. 5.拼接$group
  30. DBObject Group = new BasicDBObject("$group", Select);
  31. 至此。我们拼接,mongodb的语句到此结束
  32. 下面我们开始查询操作:
  33. import com.mongodb.AggregationOutput;
  34. import org.springframework.data.mongodb.core.MongoTemplate;
  35. AggregationOutput Output = mongoTemplate.getCollection("这里是mongodb的数据表名")
  36. .aggregate(Match, Group);
  37. 读取查询结果:
  38. Iterable<DBObject> map = Output.results();
  39. //遍历map
  40. for (DBObject dbObject : map) {
  41. //这里读取到的map为{"_id":{"userId":1,"status"0}}...
  42. Map<String, Object> resultMap = (Map<String, Object>) dbObject.get("_id");
  43. //这里截取掉.0
  44. Integer userId = Integer.parseInt(CommUtil.toString(ausgMap.get("userId")).replace(".0",""));
  45. //在这里我们就可以对我们的数据进行操作了;
  46. Integer count = Integer.parseInt(CommUtil.toString(dbObject.get("count")));
  47. }
  48. 二、DBObject
  49. 不多说,如果大家觉得第一种方法特别长篇大论,那么下面我给大家带来一种代码更简洁的聚合查询:
  50. 直接上代码吧。
  51. 1.注意导入的包:
  52. import com.mongodb.DBObject; import com.mongodb.util.JSON;
  53. 2.$macth:
  54. (beginDay-查询开始日期;endDay-查询结束日期)
  55. DBObject match = (DBObject) JSON.parse("{$match:{'status':'1','time':
  56. {$gte:'"+beginDay+"',$lte:'"+endDay+"'}}}");
  57. 3.$group:
  58. (以userId分组,统计用户数量,累加amout字段值,取amout字段最大值)
  59. DBObject group = (DBObject) JSON.parse("{$group:{_id:'$userId',
  60. count:{$sum:1},total:{$sum:'$amount'},maxSigle:{$max:'$amount'}}}");
  61. 条件拼接完,开始查询:
  62. List<DBObject> list = new ArrayList<DBObject>();
  63. list.add(match); list.add(group);
  64. AggregationOutput Output = mongoTemplate.getCollection("表名").aggregate(list);
  65. 遍历结果就不用在说了。上面已经详细描述了
  66. 第二种方法是不是比一种方式简单多了。但是比较考验自身对mongodb语句熟悉性。
  67. 【扩展】
  68. 接着上面的方法进行扩展
  69. //status 为0或者为1 ; type 不为11;time在beginDay ~ endDay时间段内
  70. DBObject match = (DBObject) JSON.parse("{$match:{'status':{$in:['0','1']},
  71. type:{$ne:11},'time':{$gte:'"+beginDay+"',$lte:'"+endDay+"'}}}");
  72. //以用户Id分组,统计查询次数,取最后一次time的时间
  73. DBObject group = (DBObject) JSON.parse("{$group:{_id:'$userId',
  74. count:{$sum:1},lastTime:{$max:'$time'} }}");
  75. //在上一步统计出的结果中筛选次数大于100的数据
  76. DBObject groupMatch = (DBObject) JSON.parse("{$match:{count:{$gte:100}}}");
  77. //$project----查询结果中需要显示哪些字段,显示则设置为1。如下需要不显示_id 域(字段),则需如下指定:
  78. //db.集合名.aggregate( [ { $project : { _id: 0, count: 1 , lastSuccTime: 1 } } ] )
  79. DBObject project = (DBObject) JSON.parse("{$project:{_id:1,count:1,lastSuccTime:1}}");
  80. DBObject sort = (DBObject) JSON.parse("{$sort:{'count':-1}}");//排序
  81. List<DBObject> list = new ArrayList<DBObject>();
  82. list.add(match);
  83. list.add(group);
  84. list.add(groupMatch);
  85. list.add(project);
  86. list.add(sort);
  87. AggregationOutput catchOutPut = mongoTemplate.getCollection("表名")
  88. .aggregate(list);//查询结果
  89. 三、BasicDBObject+脚本语句
  90. BasicDBObject groupIndex = new BasicDBObject();
  91. BasicDBObject distinctQuery = new BasicDBObject();
  92. distinctQuery.put("userId", new BasicDBObject("$in", userIds));//UserIds数组
  93. BasicDBObject initIndex = new BasicDBObject();
  94. initIndex.put("count", 0);//给count赋初值
  95. // 脚本(doc代表数据库的数据.prev代表查询结果//prev.count这里的count就是上一步initIndex的count)
  96. String reduce = "function(doc, prev) {if(doc.status==0){prev.count+= 1;};}";
  97. List<Map<String, Object>> basicDBList = (List<Map<String, Object>>) mongoTemplate.
  98. getCollection("Collection").group(groupIndex, distinctQuery, initIndex, reduce, null);
  99. 最后循环遍历List即可得到结果【PSgroup这种聚合方式有个限制条件--->超过20000数据就会报错】
  100. 以上就是我在普通业务处理中用到mongodb聚合处理