JAVA 操作 MongoDB

释放双眼,带上耳机,听听看~!

                                          JAVA  操作 MongoDB


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
1
2import java.util.ArrayList;
3import java.util.HashMap;
4import java.util.List;
5import java.util.Map;
6import java.util.regex.Pattern;
7
8import org.bson.Document;
9
10import com.mongodb.BasicDBObject;
11import com.mongodb.MongoClient;
12import com.mongodb.client.FindIterable;
13import com.mongodb.client.MongoCollection;
14import com.mongodb.client.MongoCursor;
15import com.mongodb.client.MongoDatabase;
16import com.mongodb.client.MongoIterable;
17import com.mongodb.client.model.Filters;
18
19public class App {
20
21  private static App singleton;
22
23  private App() {
24  }
25
26  public static synchronized App getInstance() {
27      if (singleton == null) {
28          singleton = new App();
29      }
30      return singleton;
31  }
32
33  private static final String host = "127.0.0.1";
34  private static final Integer port = 27017;
35
36  public static MongoClient getMongoClient() {
37      MongoClient mongoClient = new MongoClient(host, port);
38      return mongoClient;
39  }
40
41  /**
42   * findAllDataByDatabaseNameAndTable 获取数据
43   *
44   * @param databaseName 数据库名称
45   * @param table        表名 (连接名)
46   */
47  public void findAllDataByDatabaseNameAndTable(String databaseName, String table) {
48      try {
49          MongoClient mongoClient = getMongoClient();
50          // 连接到数据库
51          MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
52          System.out.println("连接数据库" + databaseName + "成功");
53          MongoCollection<Document> collection = mongoDatabase.getCollection(table);
54          System.out.println("集合 " + table + " 选择成功");
55          FindIterable<Document> findIterable = collection.find();
56          MongoCursor<Document> mongoCursor = findIterable.iterator();
57          while (mongoCursor.hasNext()) {
58              System.out.println(mongoCursor.next().toJson());
59          }
60      } catch (Exception e) {
61          System.err.println(e.getClass().getName() + ": " + e.getMessage());
62      }
63  }
64
65  /**
66   * createCollection 创建对应的数据库的表(连接)
67   *
68   * @param databaseName 数据库名称
69   * @param table        表名(连接名)
70   */
71  public void createCollection(String databaseName, String table) {
72      try {
73          // 连接到 mongodb 服务
74          MongoClient mongoClient = getMongoClient();
75          // 连接到数据库
76          MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
77          System.out.println("连接数据库" + databaseName + "成功");
78          mongoDatabase.createCollection(table);
79          System.out.println("集合创建成功");
80      } catch (Exception e) {
81          System.err.println(e.getClass().getName() + ": " + e.getMessage());
82      }
83  }
84
85  /**
86   * getAllCollectionsBydatabaseName 获取所有的集合 根据 数据库名称
87   *
88   * @param databaseName 数据库名称
89   */
90  public void getAllCollectionsByDatabaseName(String databaseName) {
91      MongoClient mongoClient = getMongoClient();
92      MongoIterable<String> colls = mongoClient.getDatabase(databaseName).listCollectionNames();
93      for (String coll : colls) {
94          System.out.println(coll);
95      }
96  }
97
98  /**
99   * getDatabaseAll 获取所有的数据库
100  */
101 public void getDatabaseAll() {
102     try {
103         MongoClient mongoClient = getMongoClient();
104         MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
105         for (String databaseName : databaseNames) {
106             System.out.println(databaseName);
107         }
108     } catch (Exception e) {
109         System.err.println(e.getClass().getName() + ": " + e.getMessage());
110     }
111 }
112
113 /**
114  * updateDocument 更新文档数据
115  *
116  * @param databaseName 数据库名
117  * @param table        集合名称
118  * @param historyMap   历史值
119  * @param nowValue     新的值
120  */
121 public void updateDocument(String databaseName, String table, HashMap<String, String> historyMap, String nowValue) {
122     try {
123         MongoClient mongoClient = getMongoClient();
124         MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); // 连接到数据库
125         System.out.println("连接数据库" + databaseName + "成功");
126         MongoCollection<Document> collection = mongoDatabase.getCollection(table);
127         System.out.println("集合 " + table + " 选择成功");
128
129         for (Map.Entry<String, String> entry : historyMap.entrySet()) {
130             collection.updateMany(Filters.eq(entry.getKey(), entry.getValue()),
131                     new Document("$set", new Document(entry.getKey(), nowValue)));
132         }
133         FindIterable<Document> findIterable = collection.find();
134         MongoCursor<Document> mongoCursor = findIterable.iterator();
135         while (mongoCursor.hasNext()) {
136             System.out.println(mongoCursor.next());
137         }
138     } catch (Exception e) {
139         System.err.println(e.getClass().getName() + ": " + e.getMessage());
140     }
141 }
142
143 /**
144  * deleteDocument 删除文档
145  *
146  * @param databaseName 数据库名
147  * @param table        集合名称
148  * @param historyMap   历史值
149  */
150 public void deleteDocument(String databaseName, String table, HashMap<String, String> historyMap) {
151     try {
152         MongoClient mongoClient = getMongoClient();
153         MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); // 连接到数据库
154         System.out.println("连接数据库" + databaseName + "成功");
155         MongoCollection<Document> collection = mongoDatabase.getCollection(table);
156         System.out.println("集合 " + table + " 选择成功");
157
158         for (Map.Entry<String, String> map : historyMap.entrySet()) {
159             collection.deleteMany(Filters.eq(map.getKey(), map.getValue())); // 删除所有符合条件的文档
160         }
161         // collection.deleteOne(Filters.eq("likes", 200)); // 删除符合条件的第一个文档
162         // 检索查看结果
163         FindIterable<Document> findIterable = collection.find();
164         MongoCursor<Document> mongoCursor = findIterable.iterator();
165         while (mongoCursor.hasNext()) {
166             System.out.println(mongoCursor.next());
167         }
168     } catch (Exception e) {
169         System.err.println(e.getClass().getName() + ": " + e.getMessage());
170     }
171 }
172
173 /**
174  * insertDocument 新增文档
175  *
176  * @param databaseName 数据库名
177  * @param table        集合名称
178  * @param nowMap       新增的值
179  */
180 public void insertDocument(String databaseName, String table, HashMap<String, String> nowMap) {
181     try {
182         MongoClient mongoClient = getMongoClient(); // 连接到 mongodb 服务
183         MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); // 连接到数据库
184         System.out.println("连接数据库" + databaseName + "成功");
185         MongoCollection<Document> collection = mongoDatabase.getCollection(table); // 获取集合
186         System.out.println("集合 " + table + " 选择成功");
187         Document document = new Document();
188         for (Map.Entry<String, String> map : nowMap.entrySet()) {
189             document.append(map.getKey(), map.getValue());
190         }
191         List<Document> documents = new ArrayList<Document>();
192         documents.add(document);
193         collection.insertMany(documents); // 添加文档(对应的BSON数据)
194         System.out.println("数据库" + databaseName + ",集合为" + table + ",文档插入成功");
195     } catch (Exception e) {
196         System.err.println(e.getClass().getName() + ": " + e.getMessage());
197     }
198 }
199
200 /**
201  * findDataByTypeLike 模糊查询
202  *
203  * @param databaseName 数据库名称
204  * @param table        集合名称
205  * @param nowMap       参数
206  */
207 public void findDataByTypeLike(String databaseName, String table, HashMap<String, String> nowMap) {
208     MongoClient mongoClient = getMongoClient(); // 连接到 mongodb 服务
209     MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); // 连接到数据库
210     MongoCollection<Document> collection = mongoDatabase.getCollection(table); // 获取集合
211     BasicDBObject queryObject = new BasicDBObject();
212     for (Map.Entry<String, String> map : nowMap.entrySet()) {
213         Pattern queryPattern = Pattern.compile(map.getValue(), Pattern.CASE_INSENSITIVE);
214         queryObject.put(map.getKey(), queryPattern);
215     }
216     FindIterable<Document> document = collection.find(queryObject);
217     for (Document doc : document) {
218         System.out.println(doc);
219     }
220
221 }
222
223 /**
224  * findDataLimitAndLikeByPage 模糊并且分页查询
225  *
226  * @param databaseName 数据库名称
227  * @param table        集合名称
228  * @param nowMap       参数
229  * @param pageNo       页码
230  * @param pageSize     条数
231  */
232 public void findDataLimitAndLikeByPage(String databaseName, String table, HashMap<String, String> nowMap,
233         Integer pageNo, Integer pageSize) {
234     MongoClient mongoClient = getMongoClient(); // 连接到 mongodb 服务
235     MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); // 连接到数据库
236     MongoCollection<Document> collection = mongoDatabase.getCollection(table); // 获取集合
237     BasicDBObject queryObject = new BasicDBObject();
238     for (Map.Entry<String, String> map : nowMap.entrySet()) {
239         Pattern queryPattern = Pattern.compile(map.getValue(), Pattern.CASE_INSENSITIVE);
240         queryObject.put(map.getKey(), queryPattern);
241     }
242     FindIterable<Document> document = collection.find(queryObject).skip(pageNo).limit(pageSize);
243     for (Document doc : document) {
244         System.out.println(doc);
245     }
246
247 }
248
249 public static void main(String[] args) {
250     App app = App.getInstance();
251     HashMap<String, String> map = new HashMap<String, String>();
252     // map.put("name", "谢");
253     // map.put("phone", "15937469513");
254     // map.put("username", "admin");
255     // map.put("password", "123456");
256     // map.put("age", "21");
257     // map.put("address", "湖北省 恩施土家族苗族自治州 利川市");
258     // app.updateDocument("student", "user", map, "小企鹅");
259     // app.deleteDocument("student", "user", map);
260     // app.insertDocument("student", "user", map);
261     // app.findAllDataByDatabaseNameAndTable("student", "user");
262     // app.findDataByTypeLike("student", "user", map);
263
264     int pageNo = 2; // 页码
265     int pageSize = 5; // 条数
266     System.out.println("当前是第" + pageNo + "页,查询条数为" + pageSize);
267     pageNo = (pageNo - 1) * pageSize;
268     app.findDataLimitAndLikeByPage("student", "user", map, pageNo, pageSize);
269
270 }
271
272}
273
274

 

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索