0
# Collection Operations & CRUD
1
2
Complete CRUD operations with fluent query APIs, bulk operations, and advanced query capabilities for MongoDB collections with full type safety.
3
4
## Capabilities
5
6
### MongoCollection Interface
7
8
Generic collection interface providing type-safe CRUD operations and query builders.
9
10
```java { .api }
11
/**
12
* Generic MongoDB collection interface
13
* @param <TDocument> The type of documents in the collection
14
*/
15
public interface MongoCollection<TDocument> {
16
// Collection metadata
17
MongoNamespace getNamespace();
18
Class<TDocument> getDocumentClass();
19
CodecRegistry getCodecRegistry();
20
ReadPreference getReadPreference();
21
WriteConcern getWriteConcern();
22
ReadConcern getReadConcern();
23
24
// Configuration variants
25
<NewTDocument> MongoCollection<NewTDocument> withDocumentClass(Class<NewTDocument> clazz);
26
MongoCollection<TDocument> withCodecRegistry(CodecRegistry codecRegistry);
27
MongoCollection<TDocument> withReadPreference(ReadPreference readPreference);
28
MongoCollection<TDocument> withWriteConcern(WriteConcern writeConcern);
29
MongoCollection<TDocument> withReadConcern(ReadConcern readConcern);
30
}
31
```
32
33
### Insert Operations
34
35
Insert single and multiple documents into collections.
36
37
```java { .api }
38
/**
39
* Insert a single document
40
* @param document The document to insert
41
*/
42
void insertOne(TDocument document);
43
44
/**
45
* Insert a single document with options
46
* @param document The document to insert
47
* @param options Insert options
48
*/
49
void insertOne(TDocument document, InsertOneOptions options);
50
51
/**
52
* Insert a single document within a session
53
* @param clientSession The client session
54
* @param document The document to insert
55
*/
56
void insertOne(ClientSession clientSession, TDocument document);
57
58
/**
59
* Insert multiple documents
60
* @param documents List of documents to insert
61
*/
62
void insertMany(List<? extends TDocument> documents);
63
64
/**
65
* Insert multiple documents with options
66
* @param documents List of documents to insert
67
* @param options Insert options including ordered/unordered
68
*/
69
void insertMany(List<? extends TDocument> documents, InsertManyOptions options);
70
71
/**
72
* Insert multiple documents within a session
73
* @param clientSession The client session
74
* @param documents List of documents to insert
75
*/
76
void insertMany(ClientSession clientSession, List<? extends TDocument> documents);
77
```
78
79
**Insert Examples:**
80
81
```java
82
MongoCollection<Document> collection = database.getCollection("users");
83
84
// Single document insert
85
Document user = new Document("name", "Alice")
86
.append("age", 30)
87
.append("email", "alice@example.com");
88
collection.insertOne(user);
89
90
// Multiple documents insert
91
List<Document> users = Arrays.asList(
92
new Document("name", "Bob").append("age", 25),
93
new Document("name", "Charlie").append("age", 35)
94
);
95
collection.insertMany(users);
96
97
// Insert with options
98
InsertManyOptions options = new InsertManyOptions().ordered(false);
99
collection.insertMany(users, options);
100
```
101
102
### Query Operations
103
104
Find documents using filters with fluent query builders.
105
106
```java { .api }
107
/**
108
* Find all documents in the collection
109
* @return FindIterable for chaining query operations
110
*/
111
FindIterable<TDocument> find();
112
113
/**
114
* Find documents matching a filter
115
* @param filter Query filter
116
* @return FindIterable for chaining query operations
117
*/
118
FindIterable<TDocument> find(Bson filter);
119
120
/**
121
* Find documents with result type transformation
122
* @param filter Query filter
123
* @param resultClass Target result class
124
* @return FindIterable with transformed type
125
*/
126
<TResult> FindIterable<TResult> find(Bson filter, Class<TResult> resultClass);
127
128
/**
129
* Find documents within a session
130
* @param clientSession The client session
131
* @param filter Query filter
132
* @return FindIterable for chaining query operations
133
*/
134
FindIterable<TDocument> find(ClientSession clientSession, Bson filter);
135
```
136
137
### FindIterable Interface
138
139
Fluent interface for building and executing find queries.
140
141
```java { .api }
142
/**
143
* Fluent interface for find operations
144
* @param <TResult> The result document type
145
*/
146
public interface FindIterable<TResult> extends MongoIterable<TResult> {
147
// Query modification
148
FindIterable<TResult> filter(Bson filter);
149
FindIterable<TResult> limit(int limit);
150
FindIterable<TResult> skip(int skip);
151
FindIterable<TResult> maxTime(long maxTime, TimeUnit timeUnit);
152
FindIterable<TResult> batchSize(int batchSize);
153
154
// Result modification
155
FindIterable<TResult> sort(Bson sort);
156
FindIterable<TResult> projection(Bson projection);
157
158
// Cursor configuration
159
FindIterable<TResult> cursorType(CursorType cursorType);
160
FindIterable<TResult> noCursorTimeout(boolean noCursorTimeout);
161
162
// Execution
163
TResult first();
164
MongoCursor<TResult> iterator();
165
MongoCursor<TResult> cursor();
166
}
167
```
168
169
**Query Examples:**
170
171
```java
172
MongoCollection<Document> collection = database.getCollection("users");
173
174
// Find all documents
175
for (Document doc : collection.find()) {
176
System.out.println(doc.toJson());
177
}
178
179
// Find with filter
180
FindIterable<Document> iterable = collection.find(Filters.eq("status", "active"));
181
182
// Find with multiple conditions
183
FindIterable<Document> results = collection.find(
184
Filters.and(
185
Filters.gte("age", 18),
186
Filters.lt("age", 65),
187
Filters.eq("active", true)
188
)
189
);
190
191
// Find with sorting and limiting
192
List<Document> users = collection.find()
193
.sort(Sorts.descending("created"))
194
.limit(10)
195
.into(new ArrayList<>());
196
197
// Find first matching document
198
Document user = collection.find(Filters.eq("email", "alice@example.com")).first();
199
```
200
201
### Update Operations
202
203
Update single and multiple documents with flexible update operators.
204
205
```java { .api }
206
/**
207
* Update a single document
208
* @param filter Query filter to match documents
209
* @param update Update specification
210
* @return Update result with modification details
211
*/
212
UpdateResult updateOne(Bson filter, Bson update);
213
214
/**
215
* Update a single document with options
216
* @param filter Query filter to match documents
217
* @param update Update specification
218
* @param options Update options including upsert
219
* @return Update result with modification details
220
*/
221
UpdateResult updateOne(Bson filter, Bson update, UpdateOptions options);
222
223
/**
224
* Update multiple documents
225
* @param filter Query filter to match documents
226
* @param update Update specification
227
* @return Update result with modification details
228
*/
229
UpdateResult updateMany(Bson filter, Bson update);
230
231
/**
232
* Update multiple documents with options
233
* @param filter Query filter to match documents
234
* @param update Update specification
235
* @param options Update options
236
* @return Update result with modification details
237
*/
238
UpdateResult updateMany(Bson filter, Bson update, UpdateOptions options);
239
240
/**
241
* Replace a single document entirely
242
* @param filter Query filter to match document
243
* @param replacement Replacement document
244
* @return Update result with modification details
245
*/
246
UpdateResult replaceOne(Bson filter, TDocument replacement);
247
248
/**
249
* Replace a single document with options
250
* @param filter Query filter to match document
251
* @param replacement Replacement document
252
* @param options Replace options including upsert
253
* @return Update result with modification details
254
*/
255
UpdateResult replaceOne(Bson filter, TDocument replacement, ReplaceOptions options);
256
```
257
258
**Update Examples:**
259
260
```java
261
MongoCollection<Document> collection = database.getCollection("users");
262
263
// Update single document
264
UpdateResult result = collection.updateOne(
265
Filters.eq("email", "alice@example.com"),
266
Updates.set("lastLogin", new Date())
267
);
268
269
// Update multiple documents
270
collection.updateMany(
271
Filters.lt("lastLogin", oldDate),
272
Updates.set("status", "inactive")
273
);
274
275
// Update with multiple operations
276
collection.updateOne(
277
Filters.eq("_id", userId),
278
Updates.combine(
279
Updates.set("name", "Alice Smith"),
280
Updates.inc("loginCount", 1),
281
Updates.currentDate("lastModified")
282
)
283
);
284
285
// Upsert operation
286
UpdateOptions options = new UpdateOptions().upsert(true);
287
collection.updateOne(
288
Filters.eq("email", "new@example.com"),
289
Updates.set("name", "New User"),
290
options
291
);
292
```
293
294
### Delete Operations
295
296
Remove single and multiple documents from collections.
297
298
```java { .api }
299
/**
300
* Delete a single document
301
* @param filter Query filter to match document
302
* @return Delete result with count of deleted documents
303
*/
304
DeleteResult deleteOne(Bson filter);
305
306
/**
307
* Delete a single document with options
308
* @param filter Query filter to match document
309
* @param options Delete options
310
* @return Delete result with count of deleted documents
311
*/
312
DeleteResult deleteOne(Bson filter, DeleteOptions options);
313
314
/**
315
* Delete multiple documents
316
* @param filter Query filter to match documents
317
* @return Delete result with count of deleted documents
318
*/
319
DeleteResult deleteMany(Bson filter);
320
321
/**
322
* Delete multiple documents with options
323
* @param filter Query filter to match documents
324
* @param options Delete options
325
* @return Delete result with count of deleted documents
326
*/
327
DeleteResult deleteMany(Bson filter, DeleteOptions options);
328
```
329
330
**Delete Examples:**
331
332
```java
333
// Delete single document
334
DeleteResult result = collection.deleteOne(Filters.eq("_id", userId));
335
336
// Delete multiple documents
337
collection.deleteMany(Filters.eq("status", "inactive"));
338
339
// Delete with complex filter
340
collection.deleteMany(
341
Filters.and(
342
Filters.lt("lastLogin", cutoffDate),
343
Filters.ne("role", "admin")
344
)
345
);
346
```
347
348
### Count Operations
349
350
Count documents in collections with various counting strategies.
351
352
```java { .api }
353
/**
354
* Count all documents in collection (deprecated, use countDocuments)
355
* @return Document count
356
*/
357
@Deprecated
358
long count();
359
360
/**
361
* Count documents matching filter (deprecated, use countDocuments)
362
* @param filter Query filter
363
* @return Document count
364
*/
365
@Deprecated
366
long count(Bson filter);
367
368
/**
369
* Count documents matching filter
370
* @return Exact document count
371
*/
372
long countDocuments();
373
374
/**
375
* Count documents matching filter
376
* @param filter Query filter
377
* @return Exact document count
378
*/
379
long countDocuments(Bson filter);
380
381
/**
382
* Count documents with options
383
* @param filter Query filter
384
* @param options Count options including limit and skip
385
* @return Exact document count
386
*/
387
long countDocuments(Bson filter, CountOptions options);
388
389
/**
390
* Get estimated document count using collection metadata
391
* @return Estimated document count (fast but approximate)
392
*/
393
long estimatedDocumentCount();
394
395
/**
396
* Get estimated document count with options
397
* @param options Estimation options
398
* @return Estimated document count
399
*/
400
long estimatedDocumentCount(EstimatedDocumentCountOptions options);
401
```
402
403
### Distinct Operations
404
405
Find distinct values for a field across documents.
406
407
```java { .api }
408
/**
409
* Find distinct values for a field
410
* @param fieldName Field name to get distinct values for
411
* @param resultClass Class of the field values
412
* @return DistinctIterable for the distinct values
413
*/
414
<TResult> DistinctIterable<TResult> distinct(String fieldName, Class<TResult> resultClass);
415
416
/**
417
* Find distinct values for a field with filter
418
* @param fieldName Field name to get distinct values for
419
* @param filter Query filter
420
* @param resultClass Class of the field values
421
* @return DistinctIterable for the distinct values
422
*/
423
<TResult> DistinctIterable<TResult> distinct(String fieldName, Bson filter, Class<TResult> resultClass);
424
```
425
426
**Distinct Examples:**
427
428
```java
429
// Get distinct values
430
DistinctIterable<String> cities = collection.distinct("city", String.class);
431
for (String city : cities) {
432
System.out.println(city);
433
}
434
435
// Get distinct values with filter
436
DistinctIterable<Integer> ages = collection.distinct("age",
437
Filters.eq("status", "active"), Integer.class);
438
```
439
440
## Types
441
442
```java { .api }
443
/**
444
* Result of insert operations
445
*/
446
public abstract class InsertOneResult {
447
public abstract boolean wasAcknowledged();
448
public abstract BsonValue getInsertedId();
449
}
450
451
/**
452
* Result of update operations
453
*/
454
public abstract class UpdateResult {
455
public abstract boolean wasAcknowledged();
456
public abstract long getMatchedCount();
457
public abstract long getModifiedCount();
458
public abstract BsonValue getUpsertedId();
459
}
460
461
/**
462
* Result of delete operations
463
*/
464
public abstract class DeleteResult {
465
public abstract boolean wasAcknowledged();
466
public abstract long getDeletedCount();
467
}
468
469
/**
470
* Options for insert operations
471
*/
472
public final class InsertOneOptions {
473
public InsertOneOptions bypassDocumentValidation(Boolean bypassDocumentValidation);
474
public Boolean getBypassDocumentValidation();
475
}
476
477
/**
478
* Options for update operations
479
*/
480
public class UpdateOptions {
481
public UpdateOptions upsert(boolean upsert);
482
public UpdateOptions bypassDocumentValidation(Boolean bypassDocumentValidation);
483
public boolean isUpsert();
484
public Boolean getBypassDocumentValidation();
485
}
486
```