zoukankan      html  css  js  c++  java
  • 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);  

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

    (完)

  • 相关阅读:
    第一次做Java程序注意事项
    数制学习笔记
    1228作业
    1226作业(转为十进制)
    [SDOI2010] 古代猪文 (快速幂+中国剩余定理+欧拉定理+卢卡斯定理) 解题报告
    Miller-Rabin
    STL整理之set
    [HNOI2008] GT考试(DP+矩阵快速幂+KMP)
    [JZOJ4024] [佛山市选2015] 石子游戏 解题报告
    [JZOJ3383] [NOIP2013模拟] 太鼓达人 解题报告(数位欧拉)
  • 原文地址:https://www.cnblogs.com/sa-dan/p/6836483.html
Copyright © 2011-2022 走看看