0
# MongoDB Java Driver
1
2
MongoDB Java Driver is a comprehensive Java database connectivity library that provides synchronous and asynchronous APIs for connecting to and interacting with MongoDB databases. This legacy all-in-one JAR combines driver-core, driver-sync, driver-legacy, and BSON libraries into a single dependency, offering complete MongoDB functionality including CRUD operations, aggregation pipelines, GridFS file storage, change streams, transactions, and authentication mechanisms.
3
4
## Package Information
5
6
- **Package Name**: mongo-java-driver
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>org.mongodb</groupId>
13
<artifactId>mongo-java-driver</artifactId>
14
<version>3.12.14</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import com.mongodb.MongoClient;
22
import com.mongodb.client.MongoDatabase;
23
import com.mongodb.client.MongoCollection;
24
import org.bson.Document;
25
```
26
27
For modern client interface:
28
29
```java
30
import com.mongodb.client.MongoClients;
31
import com.mongodb.client.MongoClient;
32
import com.mongodb.client.MongoDatabase;
33
import com.mongodb.client.MongoCollection;
34
```
35
36
## Basic Usage
37
38
```java
39
import com.mongodb.MongoClient;
40
import com.mongodb.client.MongoDatabase;
41
import com.mongodb.client.MongoCollection;
42
import org.bson.Document;
43
44
// Connect to MongoDB
45
MongoClient mongoClient = new MongoClient("localhost", 27017);
46
MongoDatabase database = mongoClient.getDatabase("mydb");
47
MongoCollection<Document> collection = database.getCollection("users");
48
49
// Insert a document
50
Document user = new Document("name", "Alice")
51
.append("age", 30)
52
.append("email", "alice@example.com");
53
collection.insertOne(user);
54
55
// Find documents
56
for (Document doc : collection.find()) {
57
System.out.println(doc.toJson());
58
}
59
60
// Close connection
61
mongoClient.close();
62
```
63
64
## Architecture
65
66
The MongoDB Java Driver is built around several key components:
67
68
- **Client Management**: `MongoClient` provides connection pooling and cluster management
69
- **Database Operations**: `MongoDatabase` interface for database-level operations and collection access
70
- **Collection Operations**: `MongoCollection<T>` provides type-safe CRUD operations with fluent query APIs
71
- **BSON System**: Comprehensive document and type system with `Document`, `BsonDocument`, and strongly-typed `BsonValue` hierarchy
72
- **GridFS**: Specialized APIs for storing and retrieving large files using MongoDB's GridFS specification
73
- **Change Streams**: Real-time data monitoring with resumable change stream cursors
74
- **Session Management**: Client sessions enabling multi-document transactions and causally consistent reads
75
- **Legacy APIs**: Backward-compatible legacy interfaces for migration from older driver versions
76
77
## Capabilities
78
79
### Connection Management
80
81
Core client creation and connection management for MongoDB deployments including standalone servers, replica sets, and sharded clusters.
82
83
```java { .api }
84
// Legacy MongoClient (extends Mongo class)
85
public class MongoClient extends Mongo implements Closeable {
86
public MongoClient();
87
public MongoClient(String host);
88
public MongoClient(String host, int port);
89
public MongoClient(ServerAddress addr);
90
public MongoClient(List<ServerAddress> seeds);
91
public MongoClient(MongoClientURI uri);
92
93
public MongoDatabase getDatabase(String databaseName);
94
public MongoIterable<String> listDatabaseNames();
95
public void close();
96
}
97
98
// Modern client factory (recommended)
99
public final class MongoClients {
100
public static MongoClient create();
101
public static MongoClient create(String connectionString);
102
public static MongoClient create(ConnectionString connectionString);
103
public static MongoClient create(MongoClientSettings settings);
104
public static MongoClient create(ConnectionString connectionString, MongoDriverInformation mongoDriverInformation);
105
public static MongoClient create(MongoClientSettings settings, MongoDriverInformation mongoDriverInformation);
106
}
107
```
108
109
[Connection Management](./connection-management.md)
110
111
### Database Operations
112
113
Database-level operations including collection management, command execution, and database administration.
114
115
```java { .api }
116
public interface MongoDatabase {
117
String getName();
118
MongoCollection<Document> getCollection(String collectionName);
119
<TDocument> MongoCollection<TDocument> getCollection(String collectionName, Class<TDocument> documentClass);
120
121
void createCollection(String collectionName);
122
void createCollection(String collectionName, CreateCollectionOptions options);
123
MongoIterable<String> listCollectionNames();
124
ListCollectionsIterable<Document> listCollections();
125
126
Document runCommand(Bson command);
127
void drop();
128
}
129
```
130
131
[Database Operations](./database-operations.md)
132
133
### Collection Operations & CRUD
134
135
Complete CRUD operations with fluent query APIs, bulk operations, and advanced query capabilities including aggregation and indexing.
136
137
```java { .api }
138
public interface MongoCollection<TDocument> {
139
// Insert operations
140
void insertOne(TDocument document);
141
void insertMany(List<? extends TDocument> documents);
142
143
// Query operations
144
FindIterable<TDocument> find();
145
FindIterable<TDocument> find(Bson filter);
146
TDocument findOne(Bson filter);
147
148
// Update operations
149
UpdateResult updateOne(Bson filter, Bson update);
150
UpdateResult updateMany(Bson filter, Bson update);
151
UpdateResult replaceOne(Bson filter, TDocument replacement);
152
153
// Delete operations
154
DeleteResult deleteOne(Bson filter);
155
DeleteResult deleteMany(Bson filter);
156
157
// Count operations
158
long count();
159
long countDocuments();
160
long estimatedDocumentCount();
161
}
162
```
163
164
[Collection Operations & CRUD](./collection-operations.md)
165
166
### Query Building & Filters
167
168
Comprehensive query building utilities for creating MongoDB queries, filters, sorts, projections, and updates with type safety.
169
170
```java { .api }
171
// Filter builders
172
public final class Filters {
173
public static Bson eq(String fieldName, Object value);
174
public static Bson ne(String fieldName, Object value);
175
public static Bson gt(String fieldName, Object value);
176
public static Bson gte(String fieldName, Object value);
177
public static Bson lt(String fieldName, Object value);
178
public static Bson lte(String fieldName, Object value);
179
public static Bson in(String fieldName, Object... values);
180
public static Bson and(Bson... filters);
181
public static Bson or(Bson... filters);
182
}
183
184
// Update builders
185
public final class Updates {
186
public static Bson set(String fieldName, Object value);
187
public static Bson inc(String fieldName, Number amount);
188
public static Bson push(String fieldName, Object value);
189
public static Bson pull(String fieldName, Object value);
190
}
191
```
192
193
[Query Building & Filters](./query-building.md)
194
195
### Aggregation Framework
196
197
MongoDB aggregation pipeline operations with type-safe stage builders and result processing.
198
199
```java { .api }
200
public interface MongoCollection<TDocument> {
201
AggregateIterable<TDocument> aggregate(List<? extends Bson> pipeline);
202
<TResult> AggregateIterable<TResult> aggregate(List<? extends Bson> pipeline, Class<TResult> resultClass);
203
}
204
205
public final class Aggregates {
206
public static Bson match(Bson filter);
207
public static Bson project(Bson projection);
208
public static Bson sort(Bson sort);
209
public static Bson group(Object id, BsonField... fieldAccumulators);
210
public static Bson lookup(String from, String localField, String foreignField, String as);
211
public static Bson unwind(String fieldName);
212
}
213
```
214
215
[Aggregation Framework](./aggregation.md)
216
217
### GridFS File Storage
218
219
Specialized file storage system for handling large files using MongoDB's GridFS specification with streaming upload and download capabilities.
220
221
```java { .api }
222
public interface GridFSBucket {
223
ObjectId uploadFromStream(String filename, InputStream source);
224
void downloadToStream(ObjectId id, OutputStream destination);
225
226
GridFSUploadStream openUploadStream(String filename);
227
GridFSDownloadStream openDownloadStream(ObjectId id);
228
229
GridFSFindIterable find();
230
void delete(ObjectId id);
231
void rename(ObjectId id, String newFilename);
232
}
233
234
public final class GridFSBuckets {
235
public static GridFSBucket create(MongoDatabase database);
236
public static GridFSBucket create(MongoDatabase database, String bucketName);
237
}
238
```
239
240
[GridFS File Storage](./gridfs.md)
241
242
### Change Streams
243
244
Real-time data monitoring with resumable change streams for tracking database, collection, and document-level changes.
245
246
```java { .api }
247
public interface MongoClient {
248
ChangeStreamIterable<Document> watch();
249
ChangeStreamIterable<Document> watch(List<? extends Bson> pipeline);
250
<TResult> ChangeStreamIterable<TResult> watch(List<? extends Bson> pipeline, Class<TResult> resultClass);
251
}
252
253
public interface ChangeStreamIterable<TResult> extends MongoIterable<ChangeStreamDocument<TResult>> {
254
ChangeStreamIterable<TResult> fullDocument(FullDocument fullDocument);
255
ChangeStreamIterable<TResult> resumeAfter(BsonDocument resumeToken);
256
ChangeStreamIterable<TResult> startAfter(BsonDocument startAfter);
257
ChangeStreamIterable<TResult> maxAwaitTime(long maxAwaitTime, TimeUnit timeUnit);
258
}
259
```
260
261
[Change Streams](./change-streams.md)
262
263
### Sessions & Transactions
264
265
Client session management for multi-document ACID transactions and causally consistent read operations.
266
267
```java { .api }
268
public interface MongoClient {
269
ClientSession startSession();
270
ClientSession startSession(ClientSessionOptions options);
271
}
272
273
public interface ClientSession extends Closeable {
274
void startTransaction();
275
void startTransaction(TransactionOptions transactionOptions);
276
void commitTransaction();
277
void abortTransaction();
278
279
<T> T withTransaction(TransactionBody<T> transactionBody);
280
281
BsonTimestamp getOperationTime();
282
BsonDocument getClusterTime();
283
}
284
```
285
286
[Sessions & Transactions](./sessions-transactions.md)
287
288
### BSON Data Types
289
290
Comprehensive BSON document and type system providing both flexible document APIs and strongly-typed value representations.
291
292
```java { .api }
293
// Flexible document representation
294
public class Document extends LinkedHashMap<String, Object> {
295
public Document();
296
public Document(String key, Object value);
297
public Document append(String key, Object value);
298
299
public String toJson();
300
public static Document parse(String json);
301
}
302
303
// Type-safe BSON document
304
public class BsonDocument extends BsonValue implements Map<String, BsonValue> {
305
public BsonDocument();
306
public BsonDocument append(String key, BsonValue value);
307
public BsonValue get(Object key);
308
}
309
310
// BSON value hierarchy
311
public abstract class BsonValue {
312
public abstract BsonType getBsonType();
313
public boolean isString();
314
public boolean isDocument();
315
public BsonString asString();
316
public BsonDocument asDocument();
317
}
318
```
319
320
[BSON Data Types](./bson-types.md)
321
322
### Authentication & Security
323
324
Comprehensive authentication mechanisms including SCRAM, X.509 certificates, Kerberos, and client-side field-level encryption.
325
326
```java { .api }
327
public final class MongoCredential {
328
public static MongoCredential createCredential(String userName, String database, char[] password);
329
public static MongoCredential createScramSha1Credential(String userName, String source, char[] password);
330
public static MongoCredential createScramSha256Credential(String userName, String source, char[] password);
331
public static MongoCredential createMongoX509Credential(String userName);
332
public static MongoCredential createGSSAPICredential(String userName);
333
}
334
335
// Client-side encryption
336
public interface ClientEncryption extends Closeable {
337
BsonBinary encrypt(BsonValue value, EncryptOptions options);
338
BsonValue decrypt(BsonBinary encryptedValue);
339
BsonBinary createDataKey(String kmsProvider);
340
}
341
```
342
343
[Authentication & Security](./authentication-security.md)
344
345
### Configuration & Options
346
347
Client configuration options for connection pooling, read/write preferences, timeouts, and codec registries.
348
349
```java { .api }
350
public final class MongoClientOptions {
351
public static Builder builder();
352
353
public static final class Builder {
354
public Builder connectionsPerHost(int connectionsPerHost);
355
public Builder connectTimeout(int connectTimeout);
356
public Builder socketTimeout(int socketTimeout);
357
public Builder readPreference(ReadPreference readPreference);
358
public Builder writeConcern(WriteConcern writeConcern);
359
public Builder codecRegistry(CodecRegistry codecRegistry);
360
public MongoClientOptions build();
361
}
362
}
363
364
// Read preferences
365
public abstract class ReadPreference {
366
public static ReadPreference primary();
367
public static ReadPreference secondary();
368
public static ReadPreference secondaryPreferred();
369
public static ReadPreference nearest();
370
}
371
372
// Write concerns
373
public class WriteConcern {
374
public static final WriteConcern ACKNOWLEDGED;
375
public static final WriteConcern UNACKNOWLEDGED;
376
public static final WriteConcern MAJORITY;
377
}
378
```
379
380
[Configuration & Options](./configuration.md)