Docs Menu

Docs HomeKotlin Coroutine

Databases and Collections

On this page

  • Overview
  • Access a Database
  • Access a Collection
  • Specify Return Type
  • Create a Collection
  • Document Validation
  • Get a List of Collections
  • Drop a Collection
  • Specify Read Preferences, Read Concerns, and Write Concerns

In this guide, you can learn how to use MongoDB databases and collections with the MongoDB Kotlin driver.

MongoDB organizes data into a hierarchy of the following levels:

  1. Databases: Databases are the top level of data organization in a MongoDB instance.

  2. Collections: Databases are organized into collections which contain documents.

  3. Documents: Documents contain literal data such as strings, numbers, and dates, as well as other embedded documents. For more information on document field types and structure, see the Server documentation on documents.

With the MongoDB Kotlin driver, you can model data by using Kotlin data classes or by using the Document class to store and retrieve data from MongoDB.

To learn more about using data classes, see the guide on the Data Class Data Format. To learn more about using the Document class, see the guide on the Document Data Format.

Use the getDatabase() method of a MongoClient instance to access a MongoDatabase in a MongoDB instance.

The following example accesses a database named testDatabase:

val database = client.getDatabase("testDatabase")

Use the getCollection() method of a MongoDatabase instance to access a MongoCollection in a database of your connected MongoDB instance.

The following example accesses a collection named testCollection from a MongoDatabase that contains documents of type ExampleDataClass:

ExampleDataClass data model
data class ExampleDataClass(
@BsonId val id: ObjectId = ObjectId(),
val exampleProperty: String,
)
val collection = database.getCollection<ExampleDataClass>("testCollection")

Tip

If the provided collection name does not already exist in the database, MongoDB implicitly creates the collection when you first insert data into that collection.

The driver provides a way for you to specify a class for documents returned from a collection, even if it is different than the class you specified when retrieving the collection. You can specify a return class by using the MongoCollection.withDocumentClass() method.

Specifying a different return class could be useful in the following situations:

  • Your collection contains multiple data types.

  • You specify a projection that changes your data fields.

  • You cannot directly specify a return type on a method that changes the data, such as findOneAndUpdate() or findOneAndReplace().

The following example retrieves a collection that contains data represented by the Fruit data class but returns the result of a findOneAndUpdate() operation as an instance of the NewFruit class. The operation changes the name of the qty field to quantity and adds an item to the seasons array field in the document with a name value of "strawberry":

Fruit data model
data class Fruit(
@BsonId val id: Int,
val name: String,
val qty: Int,
val seasons: List<String>
)
val collection =
database.getCollection<Fruit>("fruits")
// Define a data class for returned documents
data class NewFruit(
@BsonId val id: Int,
val name: String,
val quantity: Int,
val seasons: List<String>
)
val filter = Filters.eq(Fruit::name.name, "strawberry")
val update = Updates.combine(
Updates.rename(Fruit::qty.name, "quantity"),
Updates.push(Fruit::seasons.name, "fall"),
)
val options = FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER)
// Specify the class for returned documents as the type parameter in withDocumentClass()
val result = collection
.withDocumentClass<NewFruit>()
.findOneAndUpdate(filter, update, options)
println(result)
NewFruit(id=1, name=strawberry, quantity=205, seasons=[summer, fall])

Use the createCollection() method of a MongoDatabase instance to create a collection in a database of your connected MongoDB instance.

The following example creates a collection called exampleCollection:

database.createCollection("exampleCollection")

You can specify collection options like maximum size and document validation rules using the CreateCollectionOptions class. The createCollection() method accepts an instance of CreateCollectionOptions as an optional second parameter.

Document validation provides the ability to validate documents against a series of filters during writes to a collection. You can specify these filters using the ValidationOptions class, which accepts a series of Filters instances that specify the validation rules and expressions:

val collOptions: ValidationOptions = ValidationOptions().validator(
Filters.or(
Filters.exists("title"),
Filters.exists("name")
)
)
database.createCollection(
"movies",
CreateCollectionOptions().validationOptions(collOptions)
)

For more information, see the server documentation for document validation.

You can query for a list of collections in a database using the MongoDatabase.listCollectionNames() method:

val collectionList = database.listCollectionNames().toList()
println(collectionList)
[movies, exampleCollection]

You can remove a collection from the database using the MongoCollection.drop() method:

val collection =
database.getCollection<ExampleDataClass>("movies")
collection.drop()

Warning

Dropping a Collection Deletes All Data in the Collection

Dropping a collection from your database also permanently deletes all documents within that collection and all indexes on that collection. Only drop collections that contain data that is no longer needed.

Read preferences, read concerns, and write concerns control how the driver routes read operations and waits for acknowledgment for read and write operations when connected to a MongoDB replica set. Read preferences and read concerns apply to all read operations; write concerns apply to all write operations.

MongoDatabase instances inherit their write concern, read concern, and write preference settings from the MongoClient used to create them. MongoCollection instances inherit their write concern, read concern, and write preference settings from the MongoDatabase used to create them. However, you can use the following methods to obtain an instance of a MongoDatabase or MongoCollection with a read preference, read concern, or write concern that differs from the setting they would normally inherit:

Tip

The withReadConcern(), withReadPreference(), and withWriteConcern methods create a new instance of a MongoDatabase or MongoCollection with the desired preference or concern. The MongoDatabase or MongoCollection upon which the method is called retains its original preference and concern settings.

For more information on these topics, see the following pages in the Server manual:

←  Stable APIData Formats →