java操作mongodb示例
java操作mongodb基本实现。 <!-- more -->
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697package com.demo.utils.db;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ReadPreference;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.*;
import com.mongodb.client.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.List;
public class MongoHelper {
private Logger logger = LogManager.getLogger(this);
public final static String AUTO_ID = "_id";
public final static String UpdateDate = "_UpdateDate";
public final static int MaxSize = 1000;
private String hosts;
private String databaseName;
private MongoClient masterClusterClient;
private MongoDatabase masterClusterDB;
private MongoClient readClusterClient;
private MongoDatabase readClusterDB;
public MongoHelper(String hosts, String databaseName) {
this.hosts = hosts;
this.databaseName = databaseName;
masterClusterClient = new MongoClient(new MongoClientURI(this.hosts));
masterClusterClient.setReadPreference(ReadPreference.secondaryPreferred());
masterClusterDB = masterClusterClient.getDatabase(this.databaseName);
this.readClusterClient = this.masterClusterClient;
this.readClusterDB = this.masterClusterDB;
}
public MongoHelper(String masterClusterHosts, String masterClusterDatabaseName, String readClusterHosts, String readClusterDatabaseName) {
if (StringUtils.isEmpty(masterClusterHosts)) {
throw new IllegalArgumentException("the 'masterClusterHosts' is null or empty");
}
if (StringUtils.isEmpty(masterClusterDatabaseName)) {
throw new IllegalArgumentException("the 'masterClusterDatabaseName' is null or empty");
}
if (logger.isDebugEnabled()) {
logger.debug("masterClusterHosts:{}", masterClusterHosts);
logger.debug("masterClusterDatabaseName:{}", masterClusterDatabaseName);
}
masterClusterClient = new MongoClient(new MongoClientURI(masterClusterHosts));
masterClusterClient.setReadPreference(ReadPreference.secondaryPreferred());
masterClusterDB = masterClusterClient.getDatabase(masterClusterDatabaseName);
if (StringUtils.isEmpty(readClusterHosts) || StringUtils.isEmpty(readClusterDatabaseName)) {
this.readClusterClient = this.masterClusterClient;
this.readClusterDB = this.masterClusterDB;
} else {
if (logger.isDebugEnabled()) {
logger.debug("readClusterHosts:{}", readClusterHosts);
logger.debug("readClusterDatabaseName:{}", readClusterDatabaseName);
}
if (masterClusterHosts.equals(readClusterHosts) && masterClusterDatabaseName.equals(readClusterDatabaseName)) {
this.readClusterClient = this.masterClusterClient;
this.readClusterDB = this.masterClusterDB;
} else {
readClusterClient = new MongoClient(new MongoClientURI(readClusterHosts));
readClusterDB = readClusterClient.getDatabase(readClusterDatabaseName);
}
}
}
/**
* 执行mongo命令
*
* @param document
* @return
*/
public Document runCommand(Document document) {
if (document == null || document.isEmpty()) {
throw new IllegalArgumentException("the 'document' can not be null or empty");
}
if (document.containsKey("insert") || document.containsKey("update") || document.containsKey("delete")) {
return this.masterClusterDB.runCommand(document, ReadPreference.primary());
} else {
return this.readClusterDB.runCommand(document, ReadPreference.secondaryPreferred());
}
}
/**
* 获取数据库名称列表
*
* @return 所有数据库名称列表 需要权限
*/
public List<String> getAllDBNames() {
MongoIterable<String> dbnames = masterClusterClient.listDatabaseNames();
if (dbnames == null) {
return new ArrayList<String>();
}
List<String> _list = new ArrayList<String>();
for (String s : dbnames) {
_list.add(s);
}
return _list;
}
/**
* 获取mongo集群DB实例
*
* @return
*/
public MongoDatabase getDB() {
return getDB(databaseName, false);
}
/**
* 获取mongo集群DB实例
*
* @param dbName 数据库名大小写
* @param isRead 是否读库
* @return
*/
public MongoDatabase getDB(String dbName, Boolean isRead) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = isRead ? masterClusterClient.getDatabase(dbName) : masterClusterClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* @return 查询默认DB下的所有集合
*/
public List<String> getAllCollectionNames() {
MongoIterable<String> colls = masterClusterDB.listCollectionNames();
if (colls == null) {
return new ArrayList<String>();
}
List<String> _list = new ArrayList<String>();
for (String s : colls) {
_list.add(s);
}
return _list;
}
/**
* 查询指定DB下的所有集合
*
* @param dbName 指定DB
* @return 指定DB下的所有集合名称
*/
public List<String> getAllCollectionNames(String dbName) {
MongoDatabase db = masterClusterClient.getDatabase(dbName);
if (db == null) {
return new ArrayList<String>();
}
MongoIterable<String> colls = db.listCollectionNames();
if (colls == null) {
return new ArrayList<String>();
}
List<String> _list = new ArrayList<String>();
for (String s : colls) {
_list.add(s);
}
return _list;
}
/**
* 从默认读库获取collection集合对象
*
* @param collName 集合名字大小写
* @return 集合对象
*/
private MongoCollection<Document> getCollection(String collName) {
return getCollection(collName, ReadPreference.secondaryPreferred());
}
/**
* 获取Mongodb集合
*
* @param collName 集合名称
* @param readPreference 读操作优先顺序
* @return
*/
private MongoCollection<Document> getCollection(String collName, ReadPreference readPreference) {
if (StringUtils.isEmpty(collName)) {
throw new IllegalArgumentException("the 'collName' is null or empty");
}
MongoCollection<Document> collection = this.masterClusterDB.getCollection(collName).withReadPreference(readPreference);
return collection;
}
/**
* 获取用于读的集合。readClusterDB
*
* @param collName
* @return
*/
private MongoCollection<Document> getCollectionOfRead(String collName) {
if (StringUtils.isEmpty(collName)) {
throw new IllegalArgumentException("the 'collName' is null or empty");
}
MongoCollection<Document> collection = this.readClusterDB.getCollection(collName);
return collection;
}
/**
* 获取用于写的集合。ReadPreference.primary
*
* @param collName
* @return
*/
private MongoCollection<Document> getCollectionOfWrite(String collName) {
if (StringUtils.isEmpty(collName)) {
throw new IllegalArgumentException("the 'collName' is null or empty");
}
MongoCollection<Document> collection = this.masterClusterDB.getCollection(collName).withReadPreference(ReadPreference.primary());
return collection;
}
/**
* 从默认读库获取collection集合对象
*
* @param collName 集合名字大小写
* @return 集合对象
*/
public List<Document> getDocuments(String collName, Document condition) {
final List<Document> docs = new ArrayList<>();
if (StringUtils.isEmpty(collName)) {
return docs;
}
FindIterable<Document> iterable = this.getCollectionOfRead(collName).find(condition);
iterable.forEach(new Block<Document>() {
public void apply(final Document doc) {
docs.add(doc);
}
});
return docs;
}
/**
* 向指定集合中插入一条数据
*
* @param collName 集合名称
* @param doc 要插入的数据
* @return 是否插入成功
*/
public String insertOne(String collName, Document doc) {
MongoCollection<Document> collection = this.getCollectionOfWrite(collName);
if (collection == null) {
return null;
}
doc.append(UpdateDate, DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS"));
collection.insertOne(doc);
if (doc.containsKey(MongoHelper.AUTO_ID)) {
return doc.get(MongoHelper.AUTO_ID).toString();
}
return null;
}
/**
* 向指定集合中插入多条数据
*
* @param collName 集合名称
* @param docs 要插入的数据集合
* @return 插入是否成功
*/
public boolean insertMany(String collName, List<Document> docs) {
MongoCollection<Document> collection = this.getCollectionOfWrite(collName);
if (collection == null) {
return false;
}
String dateStr = DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS");
for (Document doc : docs) {
doc.append(UpdateDate, dateStr);
}
collection.insertMany(docs);
return true;
}
/**
* 查询集合的第一个文档
*
* @param collName 集合名称
* @return 返回第一个文档
*/
public Document findOne(String collName) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll.find().limit(1);
if (iterable == null) {
return null;
}
return iterable.first();
}
/**
* 查询文档
*
* @param collName
* @param filter
* @return
*/
public Document findOne(String collName, Bson filter) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll.find(filter).limit(1);
if (iterable == null) {
return null;
}
return iterable.first();
}
/**
* 查询文档
*
* @param collName 集合名称
* @param filter 过滤条件
* @param fields 输出字段
* @return
*/
public Document findOne(String collName, Bson filter, String... fields) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll.find(filter).limit(1);
if (iterable == null) {
return null;
}
return iterable.projection(Projections.include(fields)).first();
}
/**
* 查询文档
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projection 字段投影
* @return
*/
public Document findOne(String collName, Bson filter, Bson projection) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll.find(filter).limit(1);
if (iterable == null) {
return null;
}
return iterable.projection(projection).first();
}
/**
* 查询文档
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projections 字段投影
* @param orderField 排序字段
* @param ascding 是否升序
* @return
*/
public Document findOne(String collName, Bson filter, Bson projections, String orderField, boolean ascding) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll
.find(filter)
.sort(ascding ? Sorts.ascending(orderField) : Sorts.descending(orderField))
.limit(1);
if (iterable == null) {
return null;
}
return iterable.projection(projections).first();
}
/**
* 查询指定id的文档
*
* @param collName 集合名称
* @param id 文档主键id
* @return
*/
public Document findRowById(String collName, String id) {
if (ObjectId.isValid(id)) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return null;
}
FindIterable<Document> iterable = coll.find(Filters.eq("_id", new ObjectId(id))).limit(1);
if (iterable == null) {
return null;
}
return iterable.first();
} else {
return null;
}
}
/**
* 查询文档集合
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projections 字段投影
* @return 最多返回 @MaxSize 个文档,避免内存占用过大。返回结果按照_id字段降序排列
*/
public List<Document> findRows(String collName, Bson filter, Bson projections) {
return findRows(collName, filter, projections, null, false);
}
/**
* 查询文档集合,并按照指定字段排序
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projections 字段投影
* @param orderField 排序字段
* @param ascding 是否升序
* @return 最多返回 @MaxSize 个文档,避免内存占用过大
*/
public List<Document> findRows(String collName, Bson filter, Bson projections, String orderField, boolean ascding) {
List<Document> list = new ArrayList<Document>();
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return list;
}
FindIterable<Document> iterable = null;
if (filter == null) {
iterable = coll.find();
} else {
iterable = coll.find(filter);
}
if (iterable == null) {
return list;
}
MongoCursor<Document> cursor = null;
try {
if (StringUtils.isEmpty(orderField)) {
if (projections == null) {
cursor = iterable
.sort(ascding ? Sorts.ascending("_id") : Sorts.descending("_id"))
.limit(MaxSize)
.iterator();
} else {
cursor = iterable.projection(projections)
.sort(ascding ? Sorts.ascending("_id") : Sorts.descending("_id"))
.limit(MaxSize)
.iterator();
}
} else {
if (projections == null) {
cursor = iterable
.sort(ascding ? Sorts.ascending(orderField) : Sorts.descending(orderField))
.limit(MaxSize)
.iterator();
} else {
cursor = iterable.projection(projections)
.sort(ascding ? Sorts.ascending(orderField) : Sorts.descending(orderField))
.limit(MaxSize)
.iterator();
}
}
if (cursor != null && cursor.hasNext()) {
while (cursor.hasNext()) {
list.add(cursor.next());
}
}
return list;
} finally {
if (cursor != null)
cursor.close();
}
}
/**
* @param collName 集合名称
* @param filter 过滤条件
* @return
*/
public long getRowsCount(String collName, Bson filter) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return 0;
}
if (filter == null) {
return coll.count();
}
return coll.count(filter);
}
/**
* 查询分页文档集合,按照_id字段降序排列
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projections 字段投影
* @param pageNo 当前页编号,从0开始
* @param pageSize 每页容量
* @return
* @throws Exception
*/
public List<Document> findPagedRows(String collName, Bson filter, Bson projections, int pageNo, int pageSize) {
return findPagedRows(collName, filter, projections, null, false, pageNo, pageSize);
}
/**
* 查询分页文档集合,默认按照_id字段排序
*
* @param collName 集合名称
* @param filter 过滤条件
* @param projections 字段投影
* @param orderField 排序字段
* @param ascding 是否升序
* @param pageNo 当前页编号,从0开始
* @param pageSize 每页容量
* @return
*/
public List<Document> findPagedRows(String collName, Bson filter, Bson projections, String orderField, boolean ascding, int pageNo, int pageSize) {
List<Document> list = new ArrayList<Document>(pageSize);
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
if (coll == null) {
return list;
}
FindIterable<Document> iterable = null;
if (filter == null) {
iterable = coll.find();
} else {
iterable = coll.find(filter);
}
if (iterable == null) {
return list;
}
MongoCursor<Document> cursor = null;
try {
if (StringUtils.isEmpty(orderField)) {
cursor = iterable.projection(projections)
.sort(ascding ? Sorts.ascending("_id") : Sorts.descending("_id"))
.skip((pageNo - 1) * pageSize)
.limit(pageSize)
.iterator();
} else {
cursor = iterable.projection(projections)
.sort(Sorts.ascending(orderField))
.sort(ascding ? Sorts.ascending(orderField) : Sorts.descending(orderField))
.skip((pageNo - 1) * pageSize)
.limit(pageSize)
.iterator();
}
if (cursor != null && cursor.hasNext()) {
while (cursor.hasNext()) {
list.add(cursor.next());
}
}
return list;
} finally {
if (cursor != null)
cursor.close();
}
}
/**
* 根据主键id删除文档
*
* @param collName 集合名称
* @param id 文档id
* @return 被删除的文档数量
*/
public long deleteById(String collName, String id) {
if (ObjectId.isValid(id)) {
MongoCollection<Document> coll = this.getCollectionOfWrite(collName);
if (coll == null) {
return 0;
}
return coll.deleteOne(Filters.eq("_id", new ObjectId(id)))
.getDeletedCount();
} else {
return 0;
}
}
/**
* 根据指定filter删除文档
*
* @param collName
* @param filter
* @return 被删除文档的数量
*/
public long delete(String collName, Bson filter) {
if (filter == null) {
return 0;
} else {
MongoCollection<Document> coll = this.getCollectionOfWrite(collName);
if (coll == null) {
return 0;
}
return coll.deleteOne(filter)
.getDeletedCount();
}
}
/**
* 更新文档
*
* @param collName 集合名称
* @param filter 过滤条件
* @param update 更新语句
* @return 更新的文档数量
*/
public long update(String collName, Bson filter, Bson update) {
MongoCollection<Document> coll = this.getCollectionOfWrite(collName);
if (coll == null) {
return 0;
}
return coll.updateOne(filter, Updates.combine(
update,
Updates.set(UpdateDate, DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS")))
).getModifiedCount();
}
/**
* 更新文档
*
* @param collName 集合名称
* @param updates 更新语句
* @return 更新的文档数量
*/
public long updateMany(String collName, List<WriteModel<Document>> updates) {
MongoCollection<Document> coll = this.getCollectionOfWrite(collName);
if (coll == null || updates == null || updates.size() == 0) {
return 0;
}
BulkWriteResult bulkWriteResult = coll.bulkWrite(updates);
return bulkWriteResult.getModifiedCount();
}
/**
* 更新文档,指定文档存在则更新,不存在则插入
*
* @param collName 集合名称
* @param filter 过滤条件
* @param update 更新语句
* @return 更新的文档数量
*/
public long upsert(String collName, Bson filter, Bson update) {
MongoCollection<Document> coll = this.getCollectionOfWrite(collName);
if (coll == null) {
return 0;
}
;
return coll.updateOne(filter, Updates.combine(
update,
Updates.set(UpdateDate, DateTime.now().toString("yyyy-MM-dd HH:mm:ss.SSS"))
),
new UpdateOptions().upsert(true)
).getModifiedCount();
}
public List<Document> aggregate(String collName, List<Bson> pipelines) {
MongoCollection<Document> coll = this.getCollectionOfRead(collName);
MongoCursor<Document> cursor = null;
List<Document> documents = new ArrayList<>();
try {
cursor = coll.aggregate(pipelines).iterator();
if (cursor != null && cursor.hasNext()) {
while (cursor.hasNext()) {
documents.add(cursor.next());
}
}
return documents;
} finally {
if (cursor != null)
cursor.close();
}
}
}