Skip to content

[Kotlin Sync] Run a Command #61

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 11 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 9 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
20 changes: 20 additions & 0 deletions source/includes/run-command.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document

fun main() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated example to include a full file

//start-execute
val commandToExplain = Document( "find", "restaurants")
val explanation = database.runCommand(Document("explain", commandToExplain))
//end-execute

//start-read-preference
val command = Document("hello", 1)
val commandReadPreference = Document( "readPreference", "secondary" )

val commandResult = database.runCommand(command, commandReadPreference)
//end-read-preference

//start-build-info
println( database.runCommand( Document( "buildInfo", 1 ) );
//end-build-info
}
1 change: 1 addition & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
Aggregation Operations </agg-exp-ops>
Specialized Data Formats </data-formats>
Builders </builders>
Run a Command </run-command>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move the Run a Command page under a top-level drawer named Databases and Collections? Similar to how we do it in Scala and [C])https://www.mongodb.com/docs/languages/c/c-driver/current/databases-collections/run-command/). The Databases and Collections page can be empty for now.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to leave this here based on conversations with Caitlin and Sarah Lin around the unified TOC. This is definitely a weird L1 topic, but it's where we landed. I agree that it's a weird place for it.

Security </security>
In-Use Encryption </encrypt-fields>
Compatibility </compatibility>
Expand Down
163 changes: 163 additions & 0 deletions source/run-command.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
.. _kotlin-run-command:

=============
Run a Command
=============

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to run a database command with the
{+driver-short+}. You can use database commands to perform a variety of
administrative and diagnostic tasks, such as fetching server statistics,
initializing a replica set, or running an aggregation pipeline.

.. important:: Prefer Driver Methods to Database Commands

The driver provides wrapper methods for many database commands.
We recommend using driver methods instead of executing database
commands when possible.

To perform administrative tasks, use the :mongosh:`MongoDB Shell </>`
instead of the {+driver-short+}. Calling the ``db.runCommand()``
method inside the shell is the preferred method to issue database
commands, as it provides a consistent interface between the shell and
drivers.

Execute a Command
-----------------

To run a database command, specify the command and any relevant
parameters in a document, then pass the document to the ``runCommand()`` method.

The following code shows how you can use the ``runCommand()``
method to run the ``explain`` command, which returns a description of how the
``find`` command will be executed if you call it:

.. literalinclude:: /includes/run-command.kt
:start-after: start-execute
:end-before: end-execute
:language: kotlin
:copyable:
:dedent:

For a full list of database commands and corresponding parameters, see
the :manual:`Database Commands </reference/command/>` guide.

.. _kotlin-command-options:

Command Options
---------------

You can specify optional command behavior for the ``runCommand()`` method by
including a ``readPreference`` parameter. The following example shows how to
specify a read preference and pass it as an option to the ``runCommand()``
method:

.. literalinclude:: /includes/run-command.kt
:start-after: start-read-preference
:end-before: end-read-preference
:language: kotlin
:copyable:
:dedent:

For more information on read preference options, see :manual:`Read Preference
</core/read-preference/>` in the Server manual.

.. note::

The ``runCommand()`` method ignores the read preference setting you may have set
on your ``database`` object. If no read preference is specified, this method
uses the ``primary`` read preference.

Response

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this section is present in the current Java https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/command/ or Coroutine version https://www.mongodb.com/docs/drivers/kotlin/coroutine/current/usage-examples/command/
I think it will be valuable to add this section to the other JVM drivers.

--------

The ``runCommand()`` method returns a ``Document`` object that contains
the response from the database after the command has been executed. Each
database command performs a different function, so the response content
can vary across commands. However, every response contains documents
with the following fields:

.. list-table::
:header-rows: 1
:widths: 30 70

* - Field
- Description

* - <command result>
- Provides fields specific to the database command. For example,
``count`` returns the ``n`` field and ``explain`` returns the
``queryPlanner`` field.

* - ``ok``
- Indicates whether the command has succeeded (``1``)
or failed (``0``).

* - ``operationTime``
- Indicates the logical time of the operation. MongoDB uses the
logical time to order operations.
To learn more about logical time, see our
:website:`blog post about the Global Logical Clock </blog/post/transactions-background-part-4-the-global-logical-clock>`.

* - ``$clusterTime``
- Provides a document that returns the signed cluster time. Cluster time is a
logical time used for ordering of operations.

The document contains the following fields:

- ``clusterTime``, which is the timestamp of the highest known cluster time for the member.
- ``signature``, which is a document that contains the hash of the cluster time and the ID
of the key used to sign the cluster time.

Example
-------

The following code shows the general output format of the ``buildInfo`` command:

.. io-code-block::

.. input:: /includes/run-command.kt
:start-after: start-build-info
:end-before: end-build-info
:language: kotlin
:dedent:

.. output::
:visible: false

{
version: '8.0.4',
<other command results>
storageEngines: [ ... ],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1737993450, i: 32 }),
signature: {
...
}
},
operationTime: Timestamp({ ... })
}



.. _addl-info-runcommand:

Additional Information
----------------------

For more information about the concepts in this guide, see the following documentation:

- `Kotlin Sync API runCommand() <{+api+}/com.mongodb.kotlin.client/-mongo-database/run-command.html>`__
- :manual:`Database Commands </reference/command/>`
- :manual:`explain Command </reference/command/explain/>`
- :manual:`hello Command </reference/command/hello/>`
- :manual:`buildInfo Command </reference/command/buildInfo/#mongodb-dbcommand-dbcmd.buildInfo>`
Loading