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


轉載,原文連接:http://blog.csdn.net/autfish/article/details/51366839

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(1, 2, 3, 4));  
  48.         Document doc4 = new Document("title", "happiness").append("owner", "tom").append("words", 1480)  
  49.                 .append("tag", Arrays.asList(2, 3, 4));  
  50.         Document doc5 = new Document("title", "a good thing").append("owner", "tom").append("words", 180)  
  51.                 .append("tag", Arrays.asList(1, 2, 3, 4, 5));  
  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()方法

注意需要靜態導入

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;

 

[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(1, 2, 3, 4)));  
  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);  

這里列出的查詢方式可以覆蓋到大部分開發需求,更多查詢需求請參考官方文檔。

(完)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM