0
# Database Operations
1
2
Database-level operations including collection management, database commands, administrative operations, and database-level aggregation and change streams.
3
4
## Capabilities
5
6
### MongoDatabase Interface
7
8
Primary interface for database-level operations providing collection management and database command execution.
9
10
```java { .api }
11
/**
12
* Interface for database-level MongoDB operations
13
*/
14
public interface MongoDatabase {
15
/**
16
* Gets the name of this database
17
* @return the database name
18
*/
19
String getName();
20
21
/**
22
* Gets a collection with default Document type
23
* @param collectionName the name of the collection
24
* @return MongoCollection instance for Document operations
25
*/
26
MongoCollection<Document> getCollection(String collectionName);
27
28
/**
29
* Gets a typed collection for custom document classes
30
* @param collectionName the name of the collection
31
* @param documentClass the class to decode each document to
32
* @return MongoCollection instance for typed operations
33
*/
34
<TDocument> MongoCollection<TDocument> getCollection(String collectionName, Class<TDocument> documentClass);
35
36
/**
37
* Executes a database command
38
* @param command the command to execute as Bson
39
* @return command result as Document
40
*/
41
Document runCommand(Bson command);
42
43
/**
44
* Executes a database command with a specific session
45
* @param clientSession the session to use for the operation
46
* @param command the command to execute as Bson
47
* @return command result as Document
48
*/
49
Document runCommand(ClientSession clientSession, Bson command);
50
51
/**
52
* Executes a database command with read preference
53
* @param command the command to execute as Bson
54
* @param readPreference the read preference for the operation
55
* @return command result as Document
56
*/
57
Document runCommand(Bson command, ReadPreference readPreference);
58
59
/**
60
* Executes a database command returning a specific type
61
* @param command the command to execute as Bson
62
* @param clazz the class to decode the result to
63
* @return command result as specified type
64
*/
65
<TResult> TResult runCommand(Bson command, Class<TResult> clazz);
66
}
67
```
68
69
**Usage Examples:**
70
71
```java
72
import com.mongodb.client.MongoDatabase;
73
import com.mongodb.client.MongoCollection;
74
import org.bson.Document;
75
76
// Get collections
77
MongoCollection<Document> products = database.getCollection("products");
78
MongoCollection<User> users = database.getCollection("users", User.class);
79
80
// Execute database commands
81
Document stats = database.runCommand(new Document("dbStats", 1));
82
System.out.println("Database size: " + stats.getInteger("dataSize"));
83
84
// Create index command
85
Document createIndexCmd = new Document("createIndexes", "products")
86
.append("indexes", Arrays.asList(
87
new Document("key", new Document("category", 1)).append("name", "category_1")
88
));
89
database.runCommand(createIndexCmd);
90
```
91
92
### Collection Management
93
94
Operations for creating, listing, and managing collections within a database.
95
96
```java { .api }
97
/**
98
* Creates a new collection with default options
99
* @param collectionName the name of the collection to create
100
*/
101
void createCollection(String collectionName);
102
103
/**
104
* Creates a new collection with specific options
105
* @param collectionName the name of the collection to create
106
* @param createCollectionOptions options for collection creation
107
*/
108
void createCollection(String collectionName, CreateCollectionOptions createCollectionOptions);
109
110
/**
111
* Creates a new collection with session support
112
* @param clientSession the session to use for the operation
113
* @param collectionName the name of the collection to create
114
* @param createCollectionOptions options for collection creation
115
*/
116
void createCollection(ClientSession clientSession, String collectionName, CreateCollectionOptions createCollectionOptions);
117
118
/**
119
* Creates a view based on an aggregation pipeline
120
* @param viewName the name of the view to create
121
* @param viewOn the source collection or view name
122
* @param pipeline the aggregation pipeline that defines the view
123
*/
124
void createView(String viewName, String viewOn, List<? extends Bson> pipeline);
125
126
/**
127
* Creates a view with additional options
128
* @param viewName the name of the view to create
129
* @param viewOn the source collection or view name
130
* @param pipeline the aggregation pipeline that defines the view
131
* @param createViewOptions options for view creation
132
*/
133
void createView(String viewName, String viewOn, List<? extends Bson> pipeline, CreateViewOptions createViewOptions);
134
135
/**
136
* Drops this database and all its collections
137
*/
138
void drop();
139
140
/**
141
* Lists all collection names in this database
142
* @return iterable of collection names
143
*/
144
ListCollectionNamesIterable listCollectionNames();
145
146
/**
147
* Lists collections with full metadata
148
* @return iterable of collection information documents
149
*/
150
ListCollectionsIterable<Document> listCollections();
151
152
/**
153
* Lists collections returning custom type
154
* @param clazz the class to decode each collection document to
155
* @return iterable of collection information objects
156
*/
157
<TResult> ListCollectionsIterable<TResult> listCollections(Class<TResult> clazz);
158
```
159
160
**Usage Examples:**
161
162
```java
163
import com.mongodb.client.model.CreateCollectionOptions;
164
import com.mongodb.client.model.ValidationOptions;
165
166
// Create simple collection
167
database.createCollection("products");
168
169
// Create collection with options
170
ValidationOptions validation = new ValidationOptions()
171
.validator(Filters.exists("name"));
172
CreateCollectionOptions options = new CreateCollectionOptions()
173
.validationOptions(validation)
174
.capped(true)
175
.maxDocuments(1000);
176
database.createCollection("logs", options);
177
178
// Create view
179
List<Bson> pipeline = Arrays.asList(
180
Aggregates.match(Filters.eq("status", "published")),
181
Aggregates.project(Projections.include("title", "author", "publishDate"))
182
);
183
database.createView("publishedArticles", "articles", pipeline);
184
185
// List collections
186
for (String collectionName : database.listCollectionNames()) {
187
System.out.println("Collection: " + collectionName);
188
}
189
190
// List with metadata
191
for (Document collectionInfo : database.listCollections()) {
192
System.out.println("Collection: " + collectionInfo.toJson());
193
}
194
```
195
196
### Database-Level Aggregation
197
198
Aggregation operations that work across multiple collections in the database.
199
200
```java { .api }
201
/**
202
* Creates an aggregation pipeline for database-level operations
203
* @param pipeline the aggregation pipeline
204
* @return AggregateIterable for executing the pipeline
205
*/
206
AggregateIterable<Document> aggregate(List<? extends Bson> pipeline);
207
208
/**
209
* Creates an aggregation pipeline returning custom type
210
* @param pipeline the aggregation pipeline
211
* @param clazz the class to decode each result document to
212
* @return AggregateIterable for executing the pipeline
213
*/
214
<TResult> AggregateIterable<TResult> aggregate(List<? extends Bson> pipeline, Class<TResult> clazz);
215
216
/**
217
* Creates an aggregation pipeline with session support
218
* @param clientSession the session to use for the operation
219
* @param pipeline the aggregation pipeline
220
* @return AggregateIterable for executing the pipeline
221
*/
222
AggregateIterable<Document> aggregate(ClientSession clientSession, List<? extends Bson> pipeline);
223
```
224
225
**Usage Examples:**
226
227
```java
228
import com.mongodb.client.model.Aggregates;
229
import com.mongodb.client.model.Accumulators;
230
231
// Database-level aggregation across collections
232
List<Bson> pipeline = Arrays.asList(
233
// Use $listCollections to get collection info
234
Aggregates.listCollections(),
235
Aggregates.match(Filters.eq("type", "collection")),
236
Aggregates.group(null, Accumulators.sum("totalCollections", 1))
237
);
238
239
for (Document result : database.aggregate(pipeline)) {
240
System.out.println("Total collections: " + result.getInteger("totalCollections"));
241
}
242
243
// Cross-collection operations with $lookup
244
List<Bson> crossCollectionPipeline = Arrays.asList(
245
// Start from one collection
246
Aggregates.match(Filters.eq("status", "active")),
247
// Lookup data from another collection
248
Aggregates.lookup("orders", "_id", "userId", "userOrders"),
249
Aggregates.project(Projections.include("name", "email", "userOrders"))
250
);
251
```
252
253
### Database-Level Change Streams
254
255
Monitor changes across all collections in a database.
256
257
```java { .api }
258
/**
259
* Creates a change stream to monitor all collections in the database
260
* @return ChangeStreamIterable for monitoring database changes
261
*/
262
ChangeStreamIterable<Document> watch();
263
264
/**
265
* Creates a change stream with aggregation pipeline
266
* @param pipeline aggregation pipeline to filter changes
267
* @return ChangeStreamIterable with filtering
268
*/
269
ChangeStreamIterable<Document> watch(List<? extends Bson> pipeline);
270
271
/**
272
* Creates a change stream returning custom type
273
* @param pipeline aggregation pipeline to filter changes
274
* @param clazz the class to decode each change document to
275
* @return ChangeStreamIterable with custom type
276
*/
277
<TResult> ChangeStreamIterable<TResult> watch(List<? extends Bson> pipeline, Class<TResult> clazz);
278
279
/**
280
* Creates a change stream with session support
281
* @param clientSession the session to use for the operation
282
* @param pipeline aggregation pipeline to filter changes
283
* @return ChangeStreamIterable with session support
284
*/
285
ChangeStreamIterable<Document> watch(ClientSession clientSession, List<? extends Bson> pipeline);
286
```
287
288
**Usage Examples:**
289
290
```java
291
// Monitor all changes in database
292
try (var cursor = database.watch().cursor()) {
293
while (cursor.hasNext()) {
294
ChangeStreamDocument<Document> change = cursor.next();
295
System.out.println("Collection: " + change.getNamespace().getCollectionName());
296
System.out.println("Operation: " + change.getOperationType());
297
System.out.println("Document: " + change.getFullDocument());
298
}
299
}
300
301
// Monitor specific operations with filter
302
List<Bson> pipeline = Arrays.asList(
303
Aggregates.match(Filters.in("operationType", Arrays.asList("insert", "update")))
304
);
305
try (var cursor = database.watch(pipeline).cursor()) {
306
while (cursor.hasNext()) {
307
ChangeStreamDocument<Document> change = cursor.next();
308
System.out.println("Change detected: " + change.getOperationType());
309
}
310
}
311
```
312
313
### Configuration Methods
314
315
Database instances support configuration chaining for operation customization.
316
317
```java { .api }
318
/**
319
* Creates a new database instance with a different codec registry
320
* @param codecRegistry the codec registry for encoding/decoding
321
* @return new MongoDatabase instance with specified codec registry
322
*/
323
MongoDatabase withCodecRegistry(CodecRegistry codecRegistry);
324
325
/**
326
* Creates a new database instance with a different read preference
327
* @param readPreference the read preference for operations
328
* @return new MongoDatabase instance with specified read preference
329
*/
330
MongoDatabase withReadPreference(ReadPreference readPreference);
331
332
/**
333
* Creates a new database instance with a different write concern
334
* @param writeConcern the write concern for operations
335
* @return new MongoDatabase instance with specified write concern
336
*/
337
MongoDatabase withWriteConcern(WriteConcern writeConcern);
338
339
/**
340
* Creates a new database instance with a different read concern
341
* @param readConcern the read concern for operations
342
* @return new MongoDatabase instance with specified read concern
343
*/
344
MongoDatabase withReadConcern(ReadConcern readConcern);
345
346
/**
347
* Creates a new database instance with a timeout
348
* @param timeout the timeout for operations
349
* @param timeUnit the time unit for the timeout
350
* @return new MongoDatabase instance with specified timeout
351
*/
352
MongoDatabase withTimeout(long timeout, TimeUnit timeUnit);
353
```
354
355
**Usage Examples:**
356
357
```java
358
import com.mongodb.ReadPreference;
359
import com.mongodb.WriteConcern;
360
import com.mongodb.ReadConcern;
361
362
// Configure database for specific requirements
363
MongoDatabase configuredDb = database
364
.withReadPreference(ReadPreference.secondaryPreferred())
365
.withWriteConcern(WriteConcern.MAJORITY)
366
.withReadConcern(ReadConcern.SNAPSHOT);
367
368
// Use configured database
369
MongoCollection<Document> collection = configuredDb.getCollection("important-data");
370
```