0
# MongoDB Java Driver - Collection CRUD Operations
1
2
## Overview
3
4
The `MongoCollection` interface provides comprehensive CRUD (Create, Read, Update, Delete) operations for working with MongoDB collections. This document covers all available operations with detailed examples and configuration options.
5
6
## Insert Operations
7
8
### insertOne
9
10
Inserts a single document into the collection.
11
12
```java { .api }
13
InsertOneResult insertOne(TDocument document)
14
InsertOneResult insertOne(TDocument document, InsertOneOptions options)
15
InsertOneResult insertOne(ClientSession clientSession, TDocument document)
16
InsertOneResult insertOne(ClientSession clientSession, TDocument document, InsertOneOptions options)
17
```
18
19
**Parameters:**
20
- `clientSession` - Client session for transaction support
21
- `document` - The document to insert
22
- `options` - Insert options (bypass document validation, etc.)
23
24
**Usage Examples:**
25
26
```java
27
// Basic insert
28
Document doc = new Document("name", "John Doe")
29
.append("email", "john@example.com")
30
.append("age", 30);
31
InsertOneResult result = collection.insertOne(doc);
32
ObjectId insertedId = result.getInsertedId().asObjectId().getValue();
33
34
// Insert with options
35
InsertOneOptions options = new InsertOneOptions()
36
.bypassDocumentValidation(true);
37
collection.insertOne(doc, options);
38
39
// Insert with session (for transactions)
40
try (ClientSession session = mongoClient.startSession()) {
41
collection.insertOne(session, doc);
42
}
43
```
44
45
### insertMany
46
47
Inserts multiple documents into the collection.
48
49
```java { .api }
50
InsertManyResult insertMany(List<? extends TDocument> documents)
51
InsertManyResult insertMany(List<? extends TDocument> documents, InsertManyOptions options)
52
InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents)
53
InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents, InsertManyOptions options)
54
```
55
56
**Parameters:**
57
- `clientSession` - Client session for transaction support
58
- `documents` - List of documents to insert
59
- `options` - Insert options (ordered, bypass document validation)
60
61
**Usage Examples:**
62
63
```java
64
// Basic batch insert
65
List<Document> documents = Arrays.asList(
66
new Document("name", "Alice").append("age", 25),
67
new Document("name", "Bob").append("age", 30),
68
new Document("name", "Charlie").append("age", 35)
69
);
70
InsertManyResult result = collection.insertMany(documents);
71
Map<Integer, BsonValue> insertedIds = result.getInsertedIds();
72
73
// Unordered insert (continue on error)
74
InsertManyOptions options = new InsertManyOptions()
75
.ordered(false)
76
.bypassDocumentValidation(true);
77
collection.insertMany(documents, options);
78
79
// Insert with session
80
try (ClientSession session = mongoClient.startSession()) {
81
collection.insertMany(session, documents);
82
}
83
```
84
85
## Query Operations
86
87
### find
88
89
Retrieves documents from the collection with optional filtering, sorting, and projection.
90
91
```java { .api }
92
FindIterable<TDocument> find()
93
FindIterable<TDocument> find(Bson filter)
94
FindIterable<TDocument> find(ClientSession clientSession)
95
FindIterable<TDocument> find(ClientSession clientSession, Bson filter)
96
<TResult> FindIterable<TResult> find(Class<TResult> resultClass)
97
<TResult> FindIterable<TResult> find(Bson filter, Class<TResult> resultClass)
98
<TResult> FindIterable<TResult> find(ClientSession clientSession, Class<TResult> resultClass)
99
<TResult> FindIterable<TResult> find(ClientSession clientSession, Bson filter, Class<TResult> resultClass)
100
```
101
102
**Parameters:**
103
- `clientSession` - Client session for transaction support
104
- `filter` - Query filter (using Filters helper)
105
- `resultClass` - Class to deserialize results into
106
107
**Usage Examples:**
108
109
```java
110
// Find all documents
111
FindIterable<Document> allDocs = collection.find();
112
for (Document doc : allDocs) {
113
System.out.println(doc.toJson());
114
}
115
116
// Find with filter
117
FindIterable<Document> adults = collection.find(Filters.gte("age", 18));
118
119
// Find with complex filter
120
Bson complexFilter = Filters.and(
121
Filters.gte("age", 25),
122
Filters.lt("age", 65),
123
Filters.eq("status", "active")
124
);
125
FindIterable<Document> results = collection.find(complexFilter);
126
127
// Find with sorting and projection
128
FindIterable<Document> sortedResults = collection.find()
129
.sort(Sorts.descending("age"))
130
.projection(Projections.include("name", "age"))
131
.limit(10)
132
.skip(5);
133
134
// Find with session
135
try (ClientSession session = mongoClient.startSession()) {
136
FindIterable<Document> sessionResults = collection.find(session, filter);
137
}
138
139
// Find into custom class
140
public class User {
141
private String name;
142
private int age;
143
// getters and setters
144
}
145
146
FindIterable<User> users = collection.find(filter, User.class);
147
```
148
149
### findOne (via find().first())
150
151
Retrieves a single document from the collection.
152
153
```java
154
// Find first matching document
155
Document firstDoc = collection.find(Filters.eq("status", "active")).first();
156
157
// Find one with session
158
Document sessionDoc = collection.find(session, filter).first();
159
```
160
161
## Update Operations
162
163
### updateOne
164
165
Updates a single document in the collection.
166
167
```java { .api }
168
UpdateResult updateOne(Bson filter, Bson update)
169
UpdateResult updateOne(Bson filter, Bson update, UpdateOptions options)
170
UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update)
171
UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update, UpdateOptions options)
172
UpdateResult updateOne(Bson filter, List<? extends Bson> update)
173
UpdateResult updateOne(Bson filter, List<? extends Bson> update, UpdateOptions options)
174
UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update)
175
UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update, UpdateOptions options)
176
```
177
178
**Parameters:**
179
- `clientSession` - Client session for transaction support
180
- `filter` - Query filter to match documents
181
- `update` - Update operations or aggregation pipeline
182
- `options` - Update options (upsert, bypass validation, etc.)
183
184
**Usage Examples:**
185
186
```java
187
// Basic update
188
Bson filter = Filters.eq("_id", objectId);
189
Bson update = Updates.set("status", "updated");
190
UpdateResult result = collection.updateOne(filter, update);
191
System.out.println("Modified count: " + result.getModifiedCount());
192
193
// Update with multiple operations
194
Bson multiUpdate = Updates.combine(
195
Updates.set("status", "active"),
196
Updates.inc("loginCount", 1),
197
Updates.currentDate("lastLogin")
198
);
199
collection.updateOne(filter, multiUpdate);
200
201
// Upsert operation
202
UpdateOptions options = new UpdateOptions().upsert(true);
203
collection.updateOne(filter, update, options);
204
205
// Update with aggregation pipeline
206
List<Bson> pipeline = Arrays.asList(
207
Aggregates.addFields(new Field("totalScore",
208
new Document("$add", Arrays.asList("$score1", "$score2"))))
209
);
210
collection.updateOne(filter, pipeline);
211
212
// Update with session
213
try (ClientSession session = mongoClient.startSession()) {
214
collection.updateOne(session, filter, update);
215
}
216
```
217
218
### updateMany
219
220
Updates multiple documents in the collection.
221
222
```java { .api }
223
UpdateResult updateMany(Bson filter, Bson update)
224
UpdateResult updateMany(Bson filter, Bson update, UpdateOptions options)
225
UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update)
226
UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update, UpdateOptions options)
227
UpdateResult updateMany(Bson filter, List<? extends Bson> update)
228
UpdateResult updateMany(Bson filter, List<? extends Bson> update, UpdateOptions options)
229
UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update)
230
UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update, UpdateOptions options)
231
```
232
233
**Usage Examples:**
234
235
```java
236
// Update multiple documents
237
Bson filter = Filters.lt("lastLogin", LocalDateTime.now().minusDays(30));
238
Bson update = Updates.set("status", "inactive");
239
UpdateResult result = collection.updateMany(filter, update);
240
System.out.println("Modified " + result.getModifiedCount() + " documents");
241
242
// Bulk status update
243
Bson bulkUpdate = Updates.combine(
244
Updates.set("status", "archived"),
245
Updates.currentDate("archivedAt")
246
);
247
collection.updateMany(Filters.eq("category", "old"), bulkUpdate);
248
```
249
250
### replaceOne
251
252
Replaces a single document in the collection.
253
254
```java { .api }
255
UpdateResult replaceOne(Bson filter, TDocument replacement)
256
UpdateResult replaceOne(Bson filter, TDocument replacement, ReplaceOptions options)
257
UpdateResult replaceOne(ClientSession clientSession, Bson filter, TDocument replacement)
258
UpdateResult replaceOne(ClientSession clientSession, Bson filter, TDocument replacement, ReplaceOptions options)
259
```
260
261
**Parameters:**
262
- `clientSession` - Client session for transaction support
263
- `filter` - Query filter to match document
264
- `replacement` - Complete replacement document
265
- `options` - Replace options (upsert, bypass validation)
266
267
**Usage Examples:**
268
269
```java
270
// Replace entire document
271
Document replacement = new Document("name", "Updated Name")
272
.append("email", "updated@example.com")
273
.append("status", "active");
274
275
Bson filter = Filters.eq("_id", objectId);
276
UpdateResult result = collection.replaceOne(filter, replacement);
277
278
// Replace with upsert
279
ReplaceOptions options = new ReplaceOptions().upsert(true);
280
collection.replaceOne(filter, replacement, options);
281
```
282
283
## Delete Operations
284
285
### deleteOne
286
287
Deletes a single document from the collection.
288
289
```java { .api }
290
DeleteResult deleteOne(Bson filter)
291
DeleteResult deleteOne(Bson filter, DeleteOptions options)
292
DeleteResult deleteOne(ClientSession clientSession, Bson filter)
293
DeleteResult deleteOne(ClientSession clientSession, Bson filter, DeleteOptions options)
294
```
295
296
**Parameters:**
297
- `clientSession` - Client session for transaction support
298
- `filter` - Query filter to match document
299
- `options` - Delete options (collation, hint)
300
301
**Usage Examples:**
302
303
```java
304
// Delete single document
305
Bson filter = Filters.eq("_id", objectId);
306
DeleteResult result = collection.deleteOne(filter);
307
System.out.println("Deleted count: " + result.getDeletedCount());
308
309
// Delete with collation
310
DeleteOptions options = new DeleteOptions()
311
.collation(Collation.builder().locale("en").build());
312
collection.deleteOne(filter, options);
313
314
// Delete with session
315
try (ClientSession session = mongoClient.startSession()) {
316
collection.deleteOne(session, filter);
317
}
318
```
319
320
### deleteMany
321
322
Deletes multiple documents from the collection.
323
324
```java { .api }
325
DeleteResult deleteMany(Bson filter)
326
DeleteResult deleteMany(Bson filter, DeleteOptions options)
327
DeleteResult deleteMany(ClientSession clientSession, Bson filter)
328
DeleteResult deleteMany(ClientSession clientSession, Bson filter, DeleteOptions options)
329
```
330
331
**Usage Examples:**
332
333
```java
334
// Delete multiple documents
335
Bson filter = Filters.lt("lastLogin", LocalDateTime.now().minusYears(1));
336
DeleteResult result = collection.deleteMany(filter);
337
System.out.println("Deleted " + result.getDeletedCount() + " inactive users");
338
339
// Delete all documents matching criteria
340
collection.deleteMany(Filters.eq("status", "expired"));
341
```
342
343
## Find-and-Modify Operations
344
345
### findOneAndDelete
346
347
Finds a single document and deletes it, returning the original document.
348
349
```java { .api }
350
TDocument findOneAndDelete(Bson filter)
351
TDocument findOneAndDelete(Bson filter, FindOneAndDeleteOptions options)
352
TDocument findOneAndDelete(ClientSession clientSession, Bson filter)
353
TDocument findOneAndDelete(ClientSession clientSession, Bson filter, FindOneAndDeleteOptions options)
354
```
355
356
**Parameters:**
357
- `clientSession` - Client session for transaction support
358
- `filter` - Query filter to match document
359
- `options` - Options (projection, sort, collation, hint)
360
361
**Usage Examples:**
362
363
```java
364
// Find and delete
365
Bson filter = Filters.eq("status", "pending");
366
Document deletedDoc = collection.findOneAndDelete(filter);
367
368
// Find and delete with sorting
369
FindOneAndDeleteOptions options = new FindOneAndDeleteOptions()
370
.sort(Sorts.ascending("priority"))
371
.projection(Projections.include("name", "priority"));
372
Document result = collection.findOneAndDelete(filter, options);
373
```
374
375
### findOneAndUpdate
376
377
Finds a single document and updates it, returning either the original or updated document.
378
379
```java { .api }
380
TDocument findOneAndUpdate(Bson filter, Bson update)
381
TDocument findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options)
382
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update)
383
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update, FindOneAndUpdateOptions options)
384
TDocument findOneAndUpdate(Bson filter, List<? extends Bson> update)
385
TDocument findOneAndUpdate(Bson filter, List<? extends Bson> update, FindOneAndUpdateOptions options)
386
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, List<? extends Bson> update)
387
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, List<? extends Bson> update, FindOneAndUpdateOptions options)
388
```
389
390
**Usage Examples:**
391
392
```java
393
// Find and update, return updated document
394
Bson filter = Filters.eq("status", "pending");
395
Bson update = Updates.combine(
396
Updates.set("status", "processing"),
397
Updates.currentDate("startedAt")
398
);
399
400
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
401
.returnDocument(ReturnDocument.AFTER)
402
.upsert(true);
403
404
Document updatedDoc = collection.findOneAndUpdate(filter, update, options);
405
```
406
407
### findOneAndReplace
408
409
Finds a single document and replaces it, returning either the original or replacement document.
410
411
```java { .api }
412
TDocument findOneAndReplace(Bson filter, TDocument replacement)
413
TDocument findOneAndReplace(Bson filter, TDocument replacement, FindOneAndReplaceOptions options)
414
TDocument findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement)
415
TDocument findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement, FindOneAndReplaceOptions options)
416
```
417
418
**Usage Examples:**
419
420
```java
421
// Find and replace
422
Document replacement = new Document("name", "New Name")
423
.append("status", "replaced");
424
425
FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
426
.returnDocument(ReturnDocument.AFTER);
427
428
Document result = collection.findOneAndReplace(filter, replacement, options);
429
```
430
431
## Count Operations
432
433
### countDocuments
434
435
Returns the count of documents that match the filter.
436
437
```java { .api }
438
long countDocuments()
439
long countDocuments(Bson filter)
440
long countDocuments(CountOptions options)
441
long countDocuments(Bson filter, CountOptions options)
442
long countDocuments(ClientSession clientSession)
443
long countDocuments(ClientSession clientSession, Bson filter)
444
long countDocuments(ClientSession clientSession, CountOptions options)
445
long countDocuments(ClientSession clientSession, Bson filter, CountOptions options)
446
```
447
448
**Parameters:**
449
- `clientSession` - Client session for transaction support
450
- `filter` - Query filter (optional)
451
- `options` - Count options (limit, skip, hint, collation)
452
453
**Usage Examples:**
454
455
```java
456
// Count all documents
457
long totalCount = collection.countDocuments();
458
459
// Count with filter
460
long activeUsers = collection.countDocuments(Filters.eq("status", "active"));
461
462
// Count with options
463
CountOptions options = new CountOptions()
464
.limit(1000)
465
.maxTime(5, TimeUnit.SECONDS);
466
long count = collection.countDocuments(filter, options);
467
```
468
469
### estimatedDocumentCount
470
471
Returns an estimate of the count of documents in the collection using collection metadata.
472
473
```java { .api }
474
long estimatedDocumentCount()
475
long estimatedDocumentCount(EstimatedDocumentCountOptions options)
476
```
477
478
**Usage Examples:**
479
480
```java
481
// Fast estimate count
482
long estimatedCount = collection.estimatedDocumentCount();
483
484
// Estimate with timeout
485
EstimatedDocumentCountOptions options = new EstimatedDocumentCountOptions()
486
.maxTime(3, TimeUnit.SECONDS);
487
long count = collection.estimatedDocumentCount(options);
488
```
489
490
## Bulk Write Operations
491
492
### bulkWrite
493
494
Executes a mix of inserts, updates, and deletes in a single batch.
495
496
```java { .api }
497
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests)
498
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests, BulkWriteOptions options)
499
BulkWriteResult bulkWrite(ClientSession clientSession, List<? extends WriteModel<? extends TDocument>> requests)
500
BulkWriteResult bulkWrite(ClientSession clientSession, List<? extends WriteModel<? extends TDocument>> requests, BulkWriteOptions options)
501
```
502
503
**Parameters:**
504
- `clientSession` - Client session for transaction support
505
- `requests` - List of write operations
506
- `options` - Bulk write options (ordered, bypass validation)
507
508
**Usage Examples:**
509
510
```java
511
// Mixed bulk operations
512
List<WriteModel<Document>> bulkOps = Arrays.asList(
513
new InsertOneModel<>(new Document("name", "New User")),
514
new UpdateOneModel<>(
515
Filters.eq("_id", objectId1),
516
Updates.set("status", "updated")
517
),
518
new DeleteOneModel<>(Filters.eq("_id", objectId2)),
519
new ReplaceOneModel<>(
520
Filters.eq("_id", objectId3),
521
new Document("name", "Replaced").append("status", "new")
522
)
523
);
524
525
BulkWriteResult result = collection.bulkWrite(bulkOps);
526
System.out.println("Inserted: " + result.getInsertedCount());
527
System.out.println("Modified: " + result.getModifiedCount());
528
System.out.println("Deleted: " + result.getDeletedCount());
529
530
// Unordered bulk write
531
BulkWriteOptions options = new BulkWriteOptions().ordered(false);
532
collection.bulkWrite(bulkOps, options);
533
```
534
535
## Collection Configuration
536
537
### withCodecRegistry
538
539
Returns a new MongoCollection instance with a different codec registry.
540
541
```java { .api }
542
<NewTDocument> MongoCollection<NewTDocument> withCodecRegistry(CodecRegistry codecRegistry)
543
```
544
545
**Usage Examples:**
546
547
```java
548
// Custom codec registry
549
CodecRegistry customRegistry = CodecRegistries.fromRegistries(
550
CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.JAVA_LEGACY)),
551
MongoClientSettings.getDefaultCodecRegistry()
552
);
553
554
MongoCollection<Document> customCollection = collection.withCodecRegistry(customRegistry);
555
```
556
557
### withReadPreference
558
559
Returns a new MongoCollection instance with a different read preference.
560
561
```java { .api }
562
MongoCollection<TDocument> withReadPreference(ReadPreference readPreference)
563
```
564
565
**Usage Examples:**
566
567
```java
568
// Read from secondary
569
MongoCollection<Document> secondaryCollection = collection
570
.withReadPreference(ReadPreference.secondary());
571
572
// Read from nearest with max staleness
573
MongoCollection<Document> nearestCollection = collection
574
.withReadPreference(ReadPreference.nearest(15, TimeUnit.SECONDS));
575
```
576
577
### withWriteConcern
578
579
Returns a new MongoCollection instance with a different write concern.
580
581
```java { .api }
582
MongoCollection<TDocument> withWriteConcern(WriteConcern writeConcern)
583
```
584
585
**Usage Examples:**
586
587
```java
588
// Majority write concern
589
MongoCollection<Document> safeCollection = collection
590
.withWriteConcern(WriteConcern.MAJORITY);
591
592
// Custom write concern
593
WriteConcern customConcern = WriteConcern.W2.withJournal(true);
594
MongoCollection<Document> customCollection = collection
595
.withWriteConcern(customConcern);
596
```
597
598
### withReadConcern
599
600
Returns a new MongoCollection instance with a different read concern.
601
602
```java { .api }
603
MongoCollection<TDocument> withReadConcern(ReadConcern readConcern)
604
```
605
606
**Usage Examples:**
607
608
```java
609
// Linearizable read concern
610
MongoCollection<Document> linearCollection = collection
611
.withReadConcern(ReadConcern.LINEARIZABLE);
612
613
// Majority read concern
614
MongoCollection<Document> majorityCollection = collection
615
.withReadConcern(ReadConcern.MAJORITY);
616
```
617
618
## Advanced Usage Patterns
619
620
### Transaction Support
621
622
All CRUD operations support MongoDB transactions when used with a ClientSession:
623
624
```java
625
try (ClientSession session = mongoClient.startSession()) {
626
TransactionOptions txnOptions = TransactionOptions.builder()
627
.readPreference(ReadPreference.primary())
628
.readConcern(ReadConcern.LOCAL)
629
.writeConcern(WriteConcern.MAJORITY)
630
.build();
631
632
session.withTransaction(() -> {
633
collection.insertOne(session, document1);
634
collection.updateOne(session, filter, update);
635
collection.deleteOne(session, deleteFilter);
636
return "Transaction completed";
637
}, txnOptions);
638
}
639
```
640
641
### Error Handling
642
643
```java
644
try {
645
InsertOneResult result = collection.insertOne(document);
646
} catch (MongoWriteException e) {
647
if (e.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
648
System.out.println("Document already exists");
649
}
650
} catch (MongoException e) {
651
System.out.println("Database error: " + e.getMessage());
652
}
653
```
654
655
### Performance Optimization
656
657
```java
658
// Use projection to limit returned fields
659
FindIterable<Document> results = collection.find(filter)
660
.projection(Projections.include("name", "status"))
661
.batchSize(1000);
662
663
// Use hint for index selection
664
collection.find(filter)
665
.hint(new Document("status", 1));
666
667
// Use allowDiskUse for large operations
668
collection.find(filter)
669
.allowDiskUse(true);
670
```
671
672
This comprehensive guide covers all the major CRUD operations available in the MongoDB Java driver's MongoCollection interface, including advanced features like transactions, bulk operations, and configuration options.