MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询


MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。

先看用于演示的类的基本代码

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. import static com.mongodb.client.model.Filters.*;  
  2. import static com.mongodb.client.model.Projections.*;  
  3. import static com.mongodb.client.model.Sorts.*;  
  4.   
  5. import java.text.ParseException;  
  6. import java.util.Arrays;  
  7.   
  8. import org.bson.BsonType;  
  9. import org.bson.Document;  
  10.   
  11. import com.mongodb.Block;  
  12. import com.mongodb.MongoClient;  
  13. import com.mongodb.client.FindIterable;  
  14. import com.mongodb.client.MongoCollection;  
  15. import com.mongodb.client.MongoDatabase;  
  16. import com.mongodb.client.model.Filters;  
  17. import com.mongodb.client.model.Projections;  
  18.   
  19. public class FindExamples {  
  20.   
  21.     public static void main(String[] args) throws ParseException {  
  22.         //根据实际环境修改ip和端口  
  23.         MongoClient mongoClient = new MongoClient("localhost"27017);  
  24.         MongoDatabase database = mongoClient.getDatabase("lesson");  
  25.           
  26.         FindExamples client = new FindExamples(database);  
  27.         client.show();  
  28.         mongoClient.close();  
  29.     }  
  30.       
  31.     private MongoDatabase database;  
  32.     public FindExamples(MongoDatabase database) {  
  33.         this.database = database;  
  34.     }  
  35.       
  36.     public void show() {  
  37.         MongoCollection<Document> mc = database.getCollection("blog");  
  38.         //每次执行前清空集合以方便重复运行  
  39.         mc.drop();  
  40.           
  41.         //插入用于测试的文档  
  42.         Document doc1 = new Document("title""good day").append("owner""tom").append("words"300)  
  43.                 .append("comments", Arrays.asList(new Document("author""joe").append("score"3).append("comment""good"), new Document("author""white").append("score"1).append("comment""oh no")));  
  44.         Document doc2 = new Document("title""good").append("owner""john").append("words"400)  
  45.                 .append("comments", Arrays.asList(new Document("author""william").append("score"4).append("comment""good"), new Document("author""white").append("score"6).append("comment""very good")));  
  46.         Document doc3 = new Document("title""good night").append("owner""mike").append("words"200)  
  47.                 .append("tag", Arrays.asList(1234));  
  48.         Document doc4 = new Document("title""happiness").append("owner""tom").append("words"1480)  
  49.                 .append("tag", Arrays.asList(234));  
  50.         Document doc5 = new Document("title""a good thing").append("owner""tom").append("words"180)  
  51.                 .append("tag", Arrays.asList(12345));  
  52.         mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));  
  53.           
  54.         //测试: 查询全部  
  55.         FindIterable<Document> iterable = mc.find();  
  56.         printResult("find all", iterable);  
  57.           
  58.         //TODO: 将在这里填充更多查询示例  
  59.     }  
  60.       
  61.     //打印查询的结果集  
  62.     public void printResult(String doing, FindIterable<Document> iterable) {  
  63.         System.out.println(doing);  
  64.         iterable.forEach(new Block<Document>() {  
  65.             public void apply(final Document document) {  
  66.                 System.out.println(document);  
  67.             }  
  68.         });  
  69.         System.out.println("------------------------------------------------------");  
  70.         System.out.println();  
  71.     }  
  72. }  
如上面代码所示,把所有的查询操作集中在show()方法中演示,并且在执行后打印结果集以观察查询结果。下面来填充show()方法

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //创建单字段索引  
  2. mc.createIndex(new Document("words"1));  
  3. //创建组合索引(同样遵循最左前缀原则)  
  4. mc.createIndex(new Document("title"1).append("owner", -1));  
  5. //创建全文索引  
  6. mc.createIndex(new Document("title""text"));  
  7.           
  8. //查询全部  
  9. FindIterable<Document> iterable = mc.find();  
  10. printResult("find all", iterable);  
  11.           
  12. //查询title=good  
  13. iterable = mc.find(new Document("title""good"));  
  14. printResult("find title=good", iterable);  
  15.           
  16. //查询title=good and owner=tom  
  17. iterable = mc.find(new Document("title""good").append("owner""tom"));  
  18. printResult("find title=good and owner=tom", iterable);  
  19.           
  20. //查询title like %good% and owner=tom  
  21. iterable = mc.find(and(regex("title""good"), eq("owner""tom")));  
  22. printResult("find title like %good% and owner=tom", iterable);  
  23.           
  24. //查询全部按title排序  
  25. iterable = mc.find().sort(ascending("title"));  
  26. printResult("find all and ascending title", iterable);  
  27.           
  28. //查询全部按owner,title排序  
  29. iterable = mc.find().sort(ascending("owner""title"));  
  30. printResult("find all and ascending owner,title", iterable);  
  31.           
  32. //查询全部按words倒序排序  
  33. iterable = mc.find().sort(descending("words"));  
  34. printResult("find all and descending words", iterable);  
  35.   
  36. //查询owner=tom or words>350  
  37. iterable = mc.find(new Document("$or", Arrays.asList(new Document("owner""tom"), new Document("words"new Document("$gt"350)))));  
  38. printResult("find owner=tom or words>350", iterable);  
  39.           
  40. //返回title和owner字段  
  41. iterable = mc.find().projection(include("title""owner"));  
  42. printResult("find all include (title,owner)", iterable);  
  43.           
  44. //返回除title外的其他字段  
  45. iterable = mc.find().projection(exclude("title"));  
  46. printResult("find all exclude title", iterable);  
  47.           
  48. //不返回_id字段  
  49. iterable = mc.find().projection(excludeId());  
  50. printResult("find all excludeId", iterable);  
  51.           
  52. //返回title和owner字段且不返回_id字段  
  53. iterable = mc.find().projection(fields(include("title""owner"), excludeId()));  
  54. printResult("find all include (title,owner) and excludeId", iterable);  
  55.           
  56. //内嵌文档匹配  
  57. iterable = mc.find(new Document("comments.author""joe"));  
  58. printResult("find comments.author=joe", iterable);  
  59.           
  60. //一个错误的示例, 想查询评论中包含作者是white且分值>2的, 返回结果不符合预期  
  61. iterable = mc.find(new Document("comments.author""white").append("comments.score"new Document("$gt"2)));  
  62. printResult("find comments.author=white and comments.score>2 (wrong)", iterable);  
  63.           
  64. //上面的需求正确的写法  
  65. iterable = mc.find(Projections.elemMatch("comments", Filters.and(Filters.eq("author""white"), Filters.gt("score"2))));  
  66. printResult("find comments.author=white and comments.score>2 using elemMatch", iterable);  
  67.           
  68. //查找title以good开头的, 并且comments只保留一个元素  
  69. iterable = mc.find(Filters.regex("title""^good")).projection(slice("comments"1));  
  70. printResult("find regex ^good and slice comments 1", iterable);  
  71.           
  72. //全文索引查找  
  73. iterable = mc.find(text("good"));  
  74. printResult("text good", iterable);  
  75.   
  76. //用Filters构建的title=good  
  77. iterable = mc.find(eq("title""good"));  
  78. printResult("Filters: title eq good", iterable);  
  79.           
  80. //$in 等同于sql的in  
  81. iterable = mc.find(in("owner""joe""john""william"));  
  82. printResult("Filters: owner in joe,john,william", iterable);  
  83.           
  84. //$nin 等同于sql的not in  
  85. iterable = mc.find(nin("owner""joe""john""tom"));  
  86. printResult("Filters: owner nin joe,john,tom", iterable);  
  87.           
  88. //查询内嵌文档  
  89. iterable = mc.find(in("comments.author""joe""tom"));  
  90. printResult("Filters: comments.author in joe,tom", iterable);  
  91.           
  92. //$ne 不等于  
  93. iterable = mc.find(ne("words"300));  
  94. printResult("Filters: words ne 300", iterable);  
  95.           
  96. //$and 组合条件  
  97. iterable = mc.find(and(eq("owner""tom"), gt("words"300)));  
  98. printResult("Filters: owner eq tom and words gt 300", iterable);  
  99.           
  100. //较复杂的组合  
  101. iterable = mc.find(and(or(eq("words"300), eq("words"400)), or(eq("owner""joe"), size("comments"2))));  
  102. printResult("Filters: (words=300 or words=400) and (owner=joe or size(comments)=2)", iterable);  
  103.           
  104. //查询第2个元素值为2的数组  
  105. iterable = mc.find(eq("tag.1"2));  
  106. printResult("Filters: tag.1 eq 2", iterable);  
  107.           
  108. //查询匹配全部值的数组  
  109. iterable = mc.find(all("tag", Arrays.asList(1234)));  
  110. printResult("Filters: tag match all (1, 2, 3, 4)", iterable);  
  111.           
  112. //$exists  
  113. iterable = mc.find(exists("tag"));  
  114. printResult("Filters: exists tag", iterable);  
  115.           
  116. iterable = mc.find(type("words", BsonType.INT32));  
  117. printResult("Filters: type words is int32", iterable);  

这里列出的查询方式可以覆盖到大部分开发需求,更多查询需求请参考官方文档。

(完)



个人补充--参考代码:

			// 先从collection中取出最后的日期
			if (queryFields.indexOf("datetime") > -1) {
				FindIterable<Document> iter = null;
				String datetime = getParam("datetime").toString();
				
				if ("last".equals(datetime)) {
					iter = collection.find().projection(Projections.include("datetime")).sort(Sorts.descending("datetime")).limit(1);
				} else {
					iter = collection.find(Filters.lte("datetime", Integer.parseInt(datetime))).projection(Projections.include("datetime")).sort(Sorts.descending("datetime")).limit(1);
				}
				
				iter.forEach(new Block<Document>() {
					public void apply(Document doc) {
						setParams("datetime", doc.getInteger("datetime"));
					}
				});
			}
			
			// 生成查询条件
			Bson[] filters = new Bson[queryFields.size()];
			for (int i=0; i<queryFields.size(); i++) {
				String field = queryFields.get(i);
				if ("objs".equals(field)) {
					List<String> objSet = getParam("objs");
					objsLen = objSet.size();
					filters[i] = Filters.in("objs", objSet);
				} else {
					switch (DataType.toData(dataTypeMap.get(field).toUpperCase())) {
						case LONG :
							filters[i] = Filters.eq(field, Long.parseLong(getParam(field).toString()));
							break;
						case DOUBLE :
							filters[i] = Filters.eq(field, Double.parseDouble(getParam(field).toString()));
							break;
						case INT :
							filters[i] = Filters.eq(field, Integer.parseInt(getParam(field).toString()));
							break;
						default :
							filters[i] = Filters.eq(field, getParam(field));
					}
				}
			}
			
			// 生成查询列名
			Bson[] projections = new Bson[2];
			fidSet = getParam("fids");
			projections[0] = Projections.include(new ArrayList<String>(fidSet));
			projections[1] = Projections.include(queryFields);
			
			// 查询mongo
			FindIterable<Document> iter = collection.find(Filters.and(filters)).projection(Projections.fields(projections));
			
			final Map<String, JSONArray> map = new HashMap<String, JSONArray>();
			
			iter.forEach(new Block<Document>() {
				public void apply(Document doc) {
					for (String seqid : seqMap.keySet()) {
						Set<String> fidSet = seqMap.get(seqid);


						JSONObject object = new JSONObject();
						object.put("objs", doc.get("objs"));
						for (String fid : fidSet) {
							if (fid.indexOf("#") > -1) {
								object.put(fid.split("#")[0], doc.get(fid));
							} else {
								object.put(fid, doc.get(fid));
							}
						}
						
						if (map.containsKey(seqid)) {
							JSONArray array = map.get(seqid);
							array.add(object);
						} else {
							JSONArray array = new JSONArray();
							array.add(object);
							map.put(seqid, array);
						}
					}
				}
			});




原文地址:

http://blog.csdn.net/autfish/article/details/51366839





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值