The MongoDB Synchronous Driver for Java providing blocking I/O patterns for database operations
npx @tessl/cli install tessl/maven-org-mongodb--mongodb-driver-sync@5.5.00
# MongoDB Java Driver (Sync)
1
2
The MongoDB Synchronous Driver for Java provides blocking I/O patterns for MongoDB database operations. It offers a comprehensive API for database and collection operations including CRUD operations, aggregation pipelines, indexing, transactions, GridFS file storage, and client-side field level encryption.
3
4
## Package Information
5
6
- **Package Name**: mongodb-driver-sync
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: `implementation 'org.mongodb:mongodb-driver-sync:5.5.1'`
10
11
## Core Imports
12
13
```java
14
import com.mongodb.client.MongoClient;
15
import com.mongodb.client.MongoClients;
16
import com.mongodb.client.MongoDatabase;
17
import com.mongodb.client.MongoCollection;
18
import org.bson.Document;
19
```
20
21
For advanced operations:
22
23
```java
24
import com.mongodb.client.ClientSession;
25
import com.mongodb.client.gridfs.GridFSBucket;
26
import com.mongodb.client.gridfs.GridFSBuckets;
27
import com.mongodb.client.vault.ClientEncryption;
28
import com.mongodb.client.vault.ClientEncryptions;
29
```
30
31
## Basic Usage
32
33
```java
34
import com.mongodb.client.MongoClient;
35
import com.mongodb.client.MongoClients;
36
import com.mongodb.client.MongoDatabase;
37
import com.mongodb.client.MongoCollection;
38
import org.bson.Document;
39
40
// Connect to MongoDB
41
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
42
43
// Get database and collection
44
MongoDatabase database = mongoClient.getDatabase("mydb");
45
MongoCollection<Document> collection = database.getCollection("mycollection");
46
47
// Insert a document
48
Document doc = new Document("name", "John Doe")
49
.append("age", 30)
50
.append("city", "New York");
51
collection.insertOne(doc);
52
53
// Find documents
54
Document found = collection.find().first();
55
System.out.println(found.toJson());
56
57
// Close connection
58
mongoClient.close();
59
```
60
61
## Architecture
62
63
The MongoDB Java driver is organized around these key components:
64
65
- **Client Management**: `MongoClients` factory and `MongoClient` for connection management
66
- **Database Operations**: `MongoDatabase` for database-level operations and collection management
67
- **Collection Operations**: `MongoCollection` for document CRUD operations, indexing, and aggregation
68
- **Query System**: Rich iterable interfaces (`FindIterable`, `AggregateIterable`) for query execution
69
- **Session Management**: `ClientSession` for transactions and causally consistent operations
70
- **GridFS**: Large file storage with `GridFSBucket` interface
71
- **Encryption**: Client-side field level encryption via `ClientEncryption`
72
73
## Capabilities
74
75
### Connection Management
76
77
Factory methods for creating MongoDB client connections with various configuration options including connection strings, settings objects, and driver information.
78
79
```java { .api }
80
public static MongoClient create();
81
public static MongoClient create(String connectionString);
82
public static MongoClient create(ConnectionString connectionString);
83
public static MongoClient create(MongoClientSettings settings);
84
```
85
86
[Connection Management](./connection-management.md)
87
88
### Database Operations
89
90
Database-level operations including collection management, database commands, aggregation pipelines, and change streams.
91
92
```java { .api }
93
public interface MongoDatabase {
94
String getName();
95
MongoCollection<Document> getCollection(String collectionName);
96
<TDocument> MongoCollection<TDocument> getCollection(String collectionName, Class<TDocument> documentClass);
97
Document runCommand(Bson command);
98
void createCollection(String collectionName);
99
void drop();
100
ListCollectionsIterable<Document> listCollections();
101
AggregateIterable<Document> aggregate(List<? extends Bson> pipeline);
102
ChangeStreamIterable<Document> watch();
103
}
104
```
105
106
[Database Operations](./database-operations.md)
107
108
### Collection CRUD Operations
109
110
Complete CRUD (Create, Read, Update, Delete) operations for documents including bulk operations, find-and-modify operations, and query execution.
111
112
```java { .api }
113
public interface MongoCollection<TDocument> {
114
// Insert operations
115
InsertOneResult insertOne(TDocument document);
116
InsertManyResult insertMany(List<? extends TDocument> documents);
117
118
// Query operations
119
FindIterable<TDocument> find();
120
FindIterable<TDocument> find(Bson filter);
121
122
// Update operations
123
UpdateResult updateOne(Bson filter, Bson update);
124
UpdateResult updateMany(Bson filter, Bson update);
125
ReplaceOneResult replaceOne(Bson filter, TDocument replacement);
126
127
// Delete operations
128
DeleteResult deleteOne(Bson filter);
129
DeleteResult deleteMany(Bson filter);
130
131
// Count operations
132
long countDocuments();
133
long estimatedDocumentCount();
134
}
135
```
136
137
[Collection CRUD Operations](./collection-crud.md)
138
139
### Query and Aggregation
140
141
Advanced querying capabilities including filtering, sorting, projection, aggregation pipelines, and MapReduce operations.
142
143
```java { .api }
144
public interface FindIterable<TResult> extends MongoIterable<TResult> {
145
FindIterable<TResult> filter(Bson filter);
146
FindIterable<TResult> sort(Bson sort);
147
FindIterable<TResult> projection(Bson projection);
148
FindIterable<TResult> limit(int limit);
149
FindIterable<TResult> skip(int skip);
150
}
151
152
public interface AggregateIterable<TResult> extends MongoIterable<TResult> {
153
void toCollection();
154
AggregateIterable<TResult> allowDiskUse(Boolean allowDiskUse);
155
Document explain();
156
}
157
```
158
159
[Query and Aggregation](./query-aggregation.md)
160
161
### Index Management
162
163
Index creation, management, and Atlas Search index operations for optimizing query performance.
164
165
```java { .api }
166
// Standard indexes
167
String createIndex(Bson keys);
168
List<String> createIndexes(List<IndexModel> indexes);
169
void dropIndex(String indexName);
170
ListIndexesIterable<Document> listIndexes();
171
172
// Atlas Search indexes
173
String createSearchIndex(String indexName, Bson definition);
174
List<String> createSearchIndexes(List<SearchIndexModel> searchIndexes);
175
ListSearchIndexesIterable<Document> listSearchIndexes();
176
```
177
178
[Index Management](./index-management.md)
179
180
### Sessions and Transactions
181
182
Client sessions for transactions, causally consistent reads, and server session management.
183
184
```java { .api }
185
public interface ClientSession extends AutoCloseable {
186
void startTransaction();
187
void startTransaction(TransactionOptions transactionOptions);
188
void commitTransaction();
189
void abortTransaction();
190
<T> T withTransaction(TransactionBody<T> transactionBody);
191
boolean hasActiveTransaction();
192
}
193
194
@FunctionalInterface
195
public interface TransactionBody<T> {
196
T execute();
197
}
198
```
199
200
[Sessions and Transactions](./sessions-transactions.md)
201
202
### Change Streams
203
204
Real-time change monitoring at cluster, database, and collection levels with resume token support.
205
206
```java { .api }
207
public interface ChangeStreamIterable<TResult> extends MongoIterable<ChangeStreamDocument<TResult>> {
208
MongoChangeStreamCursor<ChangeStreamDocument<TResult>> cursor();
209
ChangeStreamIterable<TResult> fullDocument(FullDocument fullDocument);
210
ChangeStreamIterable<TResult> resumeAfter(BsonDocument resumeToken);
211
ChangeStreamIterable<TResult> startAfter(BsonDocument startAfter);
212
}
213
```
214
215
[Change Streams](./change-streams.md)
216
217
### GridFS File Storage
218
219
Large file storage and retrieval system with streaming upload/download capabilities and file metadata management.
220
221
```java { .api }
222
public interface GridFSBucket {
223
String getBucketName();
224
int getChunkSizeBytes();
225
226
// Upload operations
227
GridFSUploadStream openUploadStream(String filename);
228
ObjectId uploadFromStream(String filename, InputStream source);
229
230
// Download operations
231
GridFSDownloadStream openDownloadStream(ObjectId id);
232
void downloadToStream(ObjectId id, OutputStream destination);
233
234
// File management
235
void delete(ObjectId id);
236
void rename(ObjectId id, String newFilename);
237
GridFSFindIterable find();
238
}
239
```
240
241
[GridFS File Storage](./gridfs.md)
242
243
### Client-Side Field Level Encryption
244
245
Client-side field level encryption for sensitive data with data key management and queryable encryption support.
246
247
```java { .api }
248
public interface ClientEncryption extends AutoCloseable {
249
// Data key management
250
BsonBinary createDataKey(String kmsProvider);
251
BsonBinary createDataKey(String kmsProvider, DataKeyOptions dataKeyOptions);
252
DeleteResult deleteKey(BsonBinary id);
253
254
// Encryption/Decryption
255
BsonBinary encrypt(BsonValue value, EncryptOptions options);
256
BsonValue decrypt(BsonBinary encryptedValue);
257
258
// Queryable encryption
259
BsonDocument encryptExpression(Bson expression, EncryptOptions options);
260
}
261
```
262
263
[Client-Side Field Level Encryption](./encryption.md)
264
265
## Types
266
267
```java { .api }
268
// Core client types
269
interface MongoClient extends MongoCluster, AutoCloseable {
270
void close();
271
ClusterDescription getClusterDescription();
272
}
273
274
interface MongoCluster {
275
MongoDatabase getDatabase(String databaseName);
276
ClientSession startSession();
277
ClientSession startSession(ClientSessionOptions options);
278
MongoIterable<String> listDatabaseNames();
279
}
280
281
// Common result types
282
class InsertOneResult {
283
BsonValue getInsertedId();
284
boolean wasAcknowledged();
285
}
286
287
class UpdateResult {
288
long getMatchedCount();
289
long getModifiedCount();
290
BsonValue getUpsertedId();
291
boolean wasAcknowledged();
292
}
293
294
class DeleteResult {
295
long getDeletedCount();
296
boolean wasAcknowledged();
297
}
298
299
// Cursor interfaces
300
interface MongoCursor<TResult> extends Iterator<TResult>, AutoCloseable {
301
TResult tryNext();
302
int available();
303
ServerCursor getServerCursor();
304
ServerAddress getServerAddress();
305
}
306
307
interface MongoChangeStreamCursor<TResult> extends MongoCursor<TResult> {
308
BsonDocument getResumeToken();
309
}
310
```