Databases and Collections
On this page
MongoDB organizes data in a hierarchical structure. A MongoDB deployment contains one or more databases, and each database contains one or more collections. In each collection, MongoDB stores data as documents that contain field-and-value pairs.
Prerequisites
You must include the following import statements in your program to run the code examples in this guide:
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import static com.mongodb.client.model.Filters.*; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.ValidationOptions;
Important
This guide uses custom Subscriber
implementations, which are
described in the Sample Custom Subscriber Implementations guide.
Connect to a MongoDB Deployment
First, connect to a running MongoDB deployment.
The following code connects to a standalone MongoDB deployment running
on localhost
on port 27017
:
MongoClient mongoClient = MongoClients.create();
To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.
Access a Database
Once you have a MongoClient
instance connected to a MongoDB
deployment, use the `getDatabase()
method to access a database.
Pass the name of the database as a parameter to the getDatabase()
method. If a database does not exist, MongoDB creates it when
you insert any data into the database.
The following example accesses the test
database:
MongoDatabase database = mongoClient.getDatabase("test");
Note
MongoDatabase
instances are immutable. To learn more, see the
Immutability section of this guide.
Access a Collection
After you create a MongoDatabase
instance, use the
getCollection()
method to access a collection from within that
database.
Pass the name of the collection as a parameter to the getCollection()
method.
Using the database
instance created in the preceding section, the
following code accesses the collection named myTestCollection
:
MongoCollection<Document> coll = database.getCollection("myTestCollection");
Note
MongoCollection
instances are immutable. To learn more, see the
Immutability section of this guide.
If a collection with that name does not exist, MongoDB creates it when you first insert data into that collection.
You can also directly create a collection with various options, such as setting the maximum size or creating documentation validation rules.
Create a Collection
The driver provides the createCollection()
method to
directly create a collection. When you create a
collection, you can specify various collection options, such as a
maximum size or documentation validation rules, with the
CreateCollectionOptions
class.
If you are not specifying any options, you do not need to directly create the collection since MongoDB automatically creates new collections when you first insert data.
Capped Collection
The following operation creates a capped collection limited to 1 megabyte:
database.createCollection( "cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000) ).subscribe(new OperationSubscriber<Void>());
To learn more about capped collections, see Capped Collections in the Server manual.
Document Validation
MongoDB allows you to validate documents during
updates and inserts. Validation rules are specified on a collection
level by using the ValidationOptions
class, which takes a
filter document that specifies the validation rules or expressions.
The following example creates a collection with schema validation:
ValidationOptions collOptions = new ValidationOptions().validator( Filters.or(Filters.exists("email"), Filters.exists("phone"))); database.createCollection( "contacts", new CreateCollectionOptions().validationOptions(collOptions) ).subscribe(new OperationSubscriber<Void>());
To learn more about document validation, see Schema Validation in the Server manual.
Get A List of Collections
You can get a list of the collections in a database by using the
MongoDatabase.listCollectionNames()
method:
database.listCollectionNames().subscribe(new PrintToStringSubscriber<String>());
Drop a Collection
You can drop a collection and delete all of the data in the collection
by using the MongoCollection.drop()
method:
MongoCollection<Document> collection = database.getCollection("contacts"); collection.drop().subscribe(new OperationSubscriber<Void>());
Immutability
MongoDatabase
and MongoCollection
instances are immutable. To
create new instances from existing instances that have different
properties, such as different read concerns, read preferences, and write concerns, the MongoDatabase
and
MongoCollection
class provides the following methods:
MongoDatabase.withReadConcern()
MongoDatabase.withReadPreference()
MongoDatabase.withWriteConcern()
MongoCollection.withReadConcern()
MongoCollection.withReadPreference()
MongoCollection.withWriteConcern()
To learn more, see the Read Data From MongoDB and Write Data to MongoDB tutorials.
CodecRegistry
An overload of the getCollection()
method allows you to specify a
different class for representing BSON documents. For example, you
might want to use the strict and type-safe BsonDocument
class to
model your documents when performing CRUD operations:
// pass BsonDocument.class as the second argument MongoCollection<BsonDocument> collection = database .getCollection("mycoll", BsonDocument.class); // insert a document BsonDocument document = BsonDocument.parse("{x: 1}"); collection.insertOne(document).subscribe(new OperationSubscriber<Void>()); document.append("x", new BsonInt32(2)).append("y", new BsonInt32(3)); // replace a document collection.replaceOne(Filters.eq("_id", document.get("_id")), document) .subscribe(new PrintSubscriber<UpdateResult>("Update Result: %s")); // find documents collection.find().subscribe(new PrintDocumentSubscriber());
There are two requirements that any class must meet to be used in this way:
Codec
instance for the class must be registered in theCodecRegistry
for theMongoCollection
.Codec
instance must be one that encodes and decodes a full BSON document, and not just, for example, a single BSON value like anInt32
.
By default, a MongoCollection
is configured with Codec
instances
for three classes:
Document
BsonDocument
BasicDBObject
Applications are free to register Codec
implementations
for other classes by customizing the CodecRegistry
. New
CodecRegistry
instances are configurable at the following levels:
In a
MongoClient
withinMongoClientSettings
In a
MongoDatabase
within itswithCodecRegistry
methodIn a
MongoCollection
within itswithCodecRegistry
method
Consider the case of encoding and decoding instances of the UUID
class. The driver by default encodes instances of UUID
by using a
byte ordering that is not compatible with other MongoDB drivers, and
changing the default would be dangerous.
It is possible for new applications that require interoperability across
multiple drivers to be able to change that default, and they can do that
by specifying a CodecRegistry
// replaces the default UuidCodec to use the standard UUID representation CodecRegistry codecRegistry = CodecRegistries.fromRegistries( CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD) ), MongoClientSettings.getDefaultCodecRegistry()); // globally MongoClientSettings settings = MongoClientSettings.builder() .codecRegistry(codecRegistry).build(); MongoClient client = MongoClients.create(settings); // or per database MongoDatabase database = client.getDatabase("mydb") .withCodecRegistry(codecRegistry); // or per collection MongoCollection<Document> collection = database.getCollection("mycoll") .withCodecRegistry(codecRegistry);