MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。
创建一个maven项目,添加依赖
1. <dependencies>
2. <dependency>
3. <groupId>org.mongodb</groupId>
4. <artifactId>mongodb-driver</artifactId>
5. 3.2.2</version>
6. </dependency>
7. </dependencies>
非maven项目可自行下载jar包
http://central.maven.org/maven2/org/mongodb/mongo-java-driver/3.2.2/mongo-java-driver-3.2.2.jar
创建基础代码测试连接
1. public class CudExamples {
2.
3. public static void main(String[] args) throws ParseException {
4. //根据实际环境修改ip和端口
5. new MongoClient("localhost", 27017);
6. "lesson");
7.
8. "language");
9. //插入一个文档
10. new Document("oop", "java"));
11. new Document("oop", "java")));
12.
13. mongoClient.close();
14. }
15. }
如果输出结果为Document{{_id=573099877bee0e1710d52f4b, oop=java}}表示环境配置正确。
改造CudExamples类以方便演示每种操作对集合的影响
1. public class CudExamples {
2.
3. public static void main(String[] args) throws ParseException {
4. new MongoClient("localhost", 27017);
5. "lesson");
6.
7. new CudExamples(database);
8. client.show();
9. mongoClient.close();
10. }
11.
12. private MongoDatabase database;
13. public CudExamples(MongoDatabase database) {
14. this.database = database;
15. }
16.
17. public void show() {
18. "language");
19. //每次执行前清空集合以方便重复运行
20. mc.drop();
21.
22. new Document("oop", "java"));
23. "insert java", mc);
24. }
25.
26. //打印查询的结果集
27. public void printCollection(String doing, MongoCollection<Document> mc) {
28. System.out.println(doing);
29. FindIterable<Document> iterable = mc.find();
30. new Block<Document>() {
31. public void apply(final Document document) {
32. System.out.println(document);
33. }
34. });
35. "------------------------------------------------------");
36. System.out.println();
37. }
38. }
如上面代码所示,把所有的操作集中在show()方法中演示,并且在执行后打印集合以观察对集合的影响。下面来填充show()方法,注意需要静态导入Updates.*
import static com.mongodb.client.model.Updates.*;
1. mc.insertOne(new Document("oop", "java"));
2. printCollection("insert java", mc);
3.
4. //插入一个包含两个字段的文档
5. Document doc = new Document("oop", "csharp").append("copyright", "microsoft");
6. mc.insertOne(doc);
7. printCollection("insert csharp", mc);
8.
9. //查找并修改一个文档
10. mc.findOneAndReplace(new Document("oop", "java"), new Document("oop", "java").append("copyright", "oracle"));
11. printCollection("findAndReplace java", mc);
12.
13. //删除一个文档
14. mc.deleteOne(new Document("oop", "java"));
15. printCollection("delete java", mc);
16.
17. //删除全部文档
18. mc.deleteMany(new Document());
19. printCollection("delete all", mc);
20.
21. //重新插入测试文档
22. mc.insertOne(new Document("oop", "java").append("copyright", "oracle"));
23. mc.insertOne(new Document("oop", "csharp").append("copyright", "microsoft"));
24. printCollection("insert java,csharp and swift", mc);
25.
26. //$set 文档中存在指定字段则修改,没有则添加
27. mc.updateMany(new Document(), set("rank", 100));
28. printCollection("$set all rank 100", mc);
29.
30. //$unset 文档中存在指定字段则删除该字段
31. mc.updateOne(new Document("oop", "csharp"), unset("rank"));
32. printCollection("unset csharp rank", mc);
33.
34. //$inc 文档中存在指定字段则相加,没有则添加
35. mc.updateOne(new Document("oop", "csharp"), inc("rank", 30));
36. printCollection("$inc csharp rank 30", mc);
37. mc.updateOne(new Document("oop", "csharp"), inc("rank", 31));
38. printCollection("$inc csharp rank 31", mc);
39.
40. //$setOnInsert 在更新时指定upsert=true并实际触发了插入操作时生效
41. mc.updateOne(new Document("oop", "swift").append("copyright", "apple"), setOnInsert("rank", 100), new UpdateOptions().upsert(true));
42. printCollection("$setOnInsert rank 100 for swift", mc);
43.
44. //$mul 相乘
45. mc.updateOne(new Document("oop", "java"), mul("rank", 0.2));
46. printCollection("$mul java rank: 0.2", mc);
47.
48. //$rename 重命名
49. mc.updateMany(new Document(), rename("rank", "ranks"));
50. printCollection("$rename all rank to ranks", mc);
51.
52. //$min 取当前值和指定值之间比较小的
53. mc.updateMany(new Document(), min("ranks", 50));
54. printCollection("$min all ranks: 50", mc);
55.
56. //$max 取当前值和指定值之间比较大的
57. mc.updateMany(new Document(), max("ranks", 40));
58. printCollection("$max all ranks: 40", mc);
59.
60. //$currentDate
61. mc.updateMany(new Document("oop", "java"), currentDate("add"));
62. printCollection("$currentDate java", mc);
63.
64. //$currentTimestamp
65. mc.updateMany(new Document("oop", "java"), currentTimestamp("lastModified"));
66. printCollection("$currentTimestamp java", mc);
67.
68. //$addToSet 添加一个元素到不重复集合
69. mc.updateMany(new Document("oop", "java"), addToSet("keywords", "for"));
70. mc.updateMany(new Document("oop", "java"), addToSet("keywords", "for"));
71. printCollection("$addToSet java keywords: for", mc);
72.
73. //$addEachToSet 添加一组元素到不重复集合
74. mc.updateMany(new Document("oop", "java"), addEachToSet("keywords", Arrays.asList("while", "true", "do", "new", "override")));
75. mc.updateMany(new Document("oop", "java"), addEachToSet("keywords", Arrays.asList("while", "true", "do", "new", "override")));
76. printCollection("$addEachToSet java keywords: while,true,do,new,override", mc);
77.
78. //$popFirst 删除第一个元素
79. mc.updateMany(new Document("oop", "java"), popFirst("keywords"));
80. printCollection("$popFirst java keywords", mc);
81.
82. //$popLast 删除最后一个元素
83. mc.updateMany(new Document("oop", "java"), popLast("keywords"));
84. printCollection("$popLast java keywords", mc);
85.
86. //$pull 删除指定元素
87. mc.updateMany(new Document("oop", "java"), pull("keywords", "new"));
88. printCollection("$pull java keywords: new", mc);
89.
90. //$pullByFilter 根据Filters删除
91. mc.updateMany(new Document("oop", "java"), pullByFilter(Filters.gte("keywords", "true")));
92. printCollection("$pullByFilter java keywords: true", mc);
93.
94. //$pullAll 删除一组元素
95. mc.updateMany(new Document("oop", "java"), pullAll("keywords", Arrays.asList("while", "true", "do", "new", "override")));
96. printCollection("$pullAll java keywords", mc);
97.
98. //$push 添加一个元素到可重复集合
99. mc.updateMany(new Document("oop", "java"), push("scores", 89));
100. printCollection("$push java scores: 89", mc);
101.
102. //$pushEach 添加一组元素到可重复集合
103. mc.updateMany(new Document("oop", "java"), pushEach("scores", Arrays.asList(89, 90, 92)));
104. printCollection("$pushEach java scores: 89,90,92", mc);
105.
106. //在集合的指定位置插入一组元素
107. mc.updateMany(new Document("oop", "java"), pushEach("scores", Arrays.asList(11, 12, 13), new PushOptions().position(0)));
108. printCollection("$pushEach java scores: 11,12,13 at position 0", mc);
109.
110. //在集合的指定位置插入一组元素并倒序排列
111. mc.updateMany(new Document("oop", "java"), pushEach("scores", Arrays.asList(40, 41), new PushOptions().sort(-1)));
112. printCollection("$pushEach java scores: 40,41 and sort(-1)", mc);
113.
114. //在集合的指定位置插入一组元素, 倒序排列后保留前3个
115. mc.updateMany(new Document("oop", "java"), pushEach("scores", Arrays.asList(60, 61), new PushOptions().sort(-1).slice(3)));
116. printCollection("$pushEach java scores: 60,61 and sort(-1) and slice(3)", mc);
117.
118. //插入一组内嵌文档
119. Bson bson = pushEach("experts",
120. new Document("first", "Rod").append("last", "Johnson"),
121. new Document("first", "Doug").append("last", "Cutting")));
122. mc.updateOne(new Document("oop", "java"), bson);
123. printCollection("$pushEach", mc);
124.
125. //combine 组合Bson
126. bson = combine(set("author", "James Gosling"), set("version", "8.0"));
127. mc.updateOne(new Document("oop", "java"), bson);
128. printCollection("$combine", mc);
(完)