diff --git a/source/databases-collections.txt b/source/databases-collections.txt index 3f85571e..2f53c0f2 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -8,4 +8,187 @@ Databases and Collections :local: :backlinks: none :depth: 2 - :class: singlecol \ No newline at end of file + :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 ` 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>`__ \ No newline at end of file diff --git a/source/includes/databases-collections.kt b/source/includes/databases-collections.kt new file mode 100644 index 00000000..d045ebb2 --- /dev/null +++ b/source/includes/databases-collections.kt @@ -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 = "" + + 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 +}