Skip to content

DOCSP-51323: Databases & collections #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 184 additions & 1 deletion source/databases-collections.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,187 @@ Databases and Collections
:local:
:backlinks: none
:depth: 2
:class: singlecol
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: table, row, organize, storage, code example

Overview
--------

In this guide, you can learn how to use MongoDB databases and
collections with the {+driver-short+}.

MongoDB organizes data into a hierarchy of the following levels:

- **Databases**: Top-level data structures in a MongoDB deployment that store collections.
- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases.
- **Documents**: Units that store literal data such as string, numbers, dates, and other embedded documents.
For more information about document field types and structure, see the
:manual:`Documents </core/document/>` guide in the {+mdb-server+} manual.

Access a Database
-----------------

To access a database, pass the database name to the ``getDatabase()``
method.

The following example accesses a database named ``test_database``:

.. literalinclude:: /includes/databases-collections.kt
:language: kotlin
:dedent:
:start-after: start-access-database
:end-before: end-access-database

.. _kotlin-sync-db-coll-access-collection:

Access a Collection
-------------------

To access a collection, pass the database name to the ``getCollection()``
method.

The following example accesses a collection named ``test_collection``:

.. literalinclude:: /includes/databases-collections.kt
:language: kotlin
:dedent:
:start-after: start-access-collection
:end-before: end-access-collection

.. tip::

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

.. _kotlin-sync-db-coll-create-collection:

Create a Collection
-------------------

To explicitly create a collection in a MongoDB database, pass a collection
name to the ``createCollection()`` method.

The following example creates a collection named ``example_collection``:

.. literalinclude:: /includes/databases-collections.kt
:language: kotlin
:dedent:
:start-after: start-create-collection
:end-before: end-create-collection

You can specify collection options, such as maximum size and document
validation rules, by setting them in a ``CreateCollectionOptions`` instance.
Then, pass the ``CreateCollectionOptions`` to the ``createCollection()`` method.
For a full list of optional parameters, see the `CreateCollectionOptions <{+core-api+}/client/model/CreateCollectionOptions.html>`__
API documentation.

Get a List of Collections
-------------------------

You can query for a list of collections in a database by calling the
``listCollections()`` method. The method returns a cursor containing all
collections in the database and their associated metadata.

The following example calls the ``listCollections()`` method and iterates over
the returned iterator to print the collections from the :ref:`kotlin-sync-db-coll-access-collection`
and :ref:`kotlin-sync-db-coll-create-collection` examples:

.. io-code-block::
:copyable: true

.. input:: /includes/databases-collections.kt
:language: kotlin
:start-after: start-find-collections
:end-before: end-find-collections
:dedent:

.. output::

{
"name": "example_collection",
"type": "collection",
"options": {},
"info": {
"readOnly": false,
...
},
"idIndex": { ... }
}
{
"name": "test_collection",
"type": "collection",
"options": {},
"info": {
"readOnly": false,
...
},
"idIndex": { ... }
}

Delete a Collection
-------------------

To delete a collection from the database, call the ``drop()`` method
on your collection.

The following example deletes the ``test_collection`` collection:

.. literalinclude:: /includes/databases-collections.kt
:language: kotlin
:dedent:
:start-after: start-drop-collection
:end-before: end-drop-collection

.. warning:: Dropping a Collection Deletes All Data in the Collection

Dropping a collection from your database permanently deletes all
documents and all indexes within that collection.

Drop a collection only if you no longer need the data in it.

.. _kotlin-sync-config-read-write:

Configure Read and Write Operations
-----------------------------------

You can control how read and write operations run on replica sets
by specifying a read preference, read concern, or write concern.

By default, databases inherit read and write settings from the ``MongoClient``
instance. Collections inherit these settings from the ``MongoClient`` or
``MongoDatabase`` instance on which the ``getCollection()`` method is called.
You can change these settings by calling the following methods:

- `MongoDatabase.withReadConcern() <{+driver-api+}/-mongo-database/with-read-concern.html>`__

- `MongoDatabase.withReadPreference() <{+driver-api+}/-mongo-database/with-read-preference.html>`__

- `MongoDatabase.withWriteConcern() <{+driver-api+}/-mongo-database/with-write-concern.html>`__

- `MongoCollection.withReadConcern() <{+driver-api+}/-mongo-collection/with-read-concern.html>`__

- `MongoCollection.withReadPreference() <{+driver-api+}/-mongo-collection/with-read-preference.html>`__

- `MongoCollection.withWriteConcern() <{+driver-api+}/-mongo-collection/with-write-concern.html>`__

To learn more about setting a read preference, read concern, and write concern,
see the :ref:`kotlin-sync-configure` guide.

API Documentation
-----------------

To learn more about any of the methods or types discussed in this
guide, see the following API documentation:

- `getDatabase() <{+driver-api+}/-mongo-cluster/get-database.html>`__
- `getCollection() <{+driver-api+}/-mongo-database/get-collection.html>`__
- `createCollection() <{+driver-api+}/-mongo-database/create-collection.html>`__
- `listCollections() <{+driver-api+}/-mongo-database/list-collections.html>`__
- `drop() <{+driver-api+}/-mongo-collection/drop.html>`__
47 changes: 47 additions & 0 deletions source/includes/databases-collections.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import org.bson.json.JsonWriterSettings

fun main() {
val uri = "<connection string URI>"

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.retryWrites(true)
.build()

val client = MongoClient.create(settings)

// Accesses the "test_database" database
// start-access-database
val db = client.getDatabase("test_database")
// end-access-database

// Accesses the "test_collection" collection
// start-access-collection
val collection = db.getCollection("test_collection")
// end-access-collection

// Explicitly creates the "example_collection" collection
// start-create-collection
db.createCollection("example_collection")
// end-create-collection

// Lists the collections in the "test_database" database
// start-find-collections
val results = db.listCollections()
val jsonSettings = JsonWriterSettings.builder().indent(true).build()

results.forEach { result ->
println(result.toJson(jsonSettings))
}
// end-find-collections


// Deletes the "test_collection" collection
// start-drop-collection
db.getCollection("test_collection").drop()
// end-drop-collection
}
Loading