Skip to content

Commit b94ee13

Browse files
authored
[Kotlin Sync] Run a Command (#61)
1 parent fed0293 commit b94ee13

File tree

3 files changed

+205
-0
lines changed

3 files changed

+205
-0
lines changed

source/includes/run-command.kt

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//start-full-example
2+
import com.mongodb.MongoException
3+
import com.mongodb.kotlin.client.MongoClient
4+
import org.bson.Document
5+
import org.bson.BsonInt64
6+
import org.bson.json.JsonWriterSettings
7+
8+
9+
fun main() {
10+
// Replace the placeholder with your MongoDB deployment's connection string
11+
val uri = "<connection string uri>"
12+
13+
val mongoClient = MongoClient.create(uri)
14+
val database = mongoClient.getDatabase("sample_mflix")
15+
try {
16+
val command = Document("buildInfo", BsonInt64(1))
17+
val commandResult = database.runCommand(command)
18+
println(commandResult.toJson(JsonWriterSettings.builder().indent(true).build()))
19+
} catch (me: MongoException) {
20+
System.err.println("An error occurred: $me")
21+
}
22+
mongoClient.close()
23+
}
24+
//end-full-example
25+
26+
fun command_examples() {
27+
//start-execute
28+
val commandToExplain = Document("find", "restaurants")
29+
val explanation = database.runCommand(Document("explain", commandToExplain))
30+
//end-execute
31+
32+
//start-read-preference
33+
val command = Document("hello", 1)
34+
val commandReadPreference = Document("readPreference", "secondary")
35+
36+
val commandResult = database.runCommand(command, commandReadPreference)
37+
//end-read-preference
38+
39+
//start-build-info
40+
println(database.runCommand(Document("buildInfo", 1));
41+
//end-build-info
42+
}

source/index.txt

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
Aggregation Operations </agg-exp-ops>
2323
Specialized Data Formats </data-formats>
2424
Builders </builders>
25+
Run a Command </run-command>
2526
Security </security>
2627
In-Use Encryption </security/encrypt-fields>
2728
Compatibility </compatibility>

source/run-command.txt

+162
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
.. _kotlin-run-command:
2+
3+
=============
4+
Run a Command
5+
=============
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to run a database command by using the
17+
{+driver-short+}. You can use database commands to perform a variety of
18+
administrative and diagnostic tasks, such as fetching server statistics,
19+
initializing a replica set, or running an aggregation pipeline.
20+
21+
.. important:: Prefer Driver Methods to Database Commands
22+
23+
The driver provides wrapper methods for many database commands.
24+
We recommend using driver methods instead of executing database
25+
commands when possible.
26+
27+
To perform administrative tasks, use the :mongosh:`MongoDB Shell </>`
28+
instead of the {+driver-short+}. Calling the ``db.runCommand()``
29+
method inside the shell is the preferred method to issue database
30+
commands, as it provides a consistent interface between the shell and
31+
drivers.
32+
33+
Execute a Command
34+
-----------------
35+
36+
To run a database command, specify the command and any relevant
37+
parameters in a document, then pass the document to the ``runCommand()`` method.
38+
39+
The following code shows how you can use the ``runCommand()``
40+
method to run the ``explain`` command, which returns a description of how the
41+
``find`` command will be executed if you call it:
42+
43+
.. literalinclude:: /includes/run-command.kt
44+
:start-after: start-execute
45+
:end-before: end-execute
46+
:language: kotlin
47+
:copyable:
48+
:dedent:
49+
50+
For a full list of database commands and corresponding parameters, see
51+
the :manual:`Database Commands </reference/command/>` guide.
52+
53+
.. _kotlin-command-options:
54+
55+
Command Options
56+
---------------
57+
58+
You can specify optional command behavior for the ``runCommand()`` method by
59+
including a ``readPreference`` parameter. The following example shows how to
60+
specify a read preference and pass it as an option to the ``runCommand()``
61+
method:
62+
63+
.. literalinclude:: /includes/run-command.kt
64+
:start-after: start-read-preference
65+
:end-before: end-read-preference
66+
:language: kotlin
67+
:copyable:
68+
:dedent:
69+
70+
For more information on read preference options, see :manual:`Read Preference
71+
</core/read-preference/>` in the Server manual.
72+
73+
.. note::
74+
75+
The ``runCommand()`` method ignores the read preference setting you may have set
76+
on your ``database`` object. If no read preference is specified, this method
77+
uses the ``primary`` read preference.
78+
79+
Response
80+
--------
81+
82+
The ``runCommand()`` method returns a ``Document`` object that contains
83+
the response from the database after the command has been executed. Each
84+
database command performs a different function, so the response content
85+
can vary across commands. However, every response contains documents
86+
with the following fields:
87+
88+
.. list-table::
89+
:header-rows: 1
90+
:widths: 30 70
91+
92+
* - Field
93+
- Description
94+
95+
* - <command result>
96+
- Provides fields specific to the database command. For example,
97+
``count`` returns the ``n`` field and ``explain`` returns the
98+
``queryPlanner`` field.
99+
100+
* - ``ok``
101+
- Indicates whether the command has succeeded (``1``)
102+
or failed (``0``).
103+
104+
* - ``operationTime``
105+
- Indicates the logical time of the operation. MongoDB uses the
106+
logical time to order operations.
107+
To learn more about logical time, see our
108+
:website:`blog post about the Global Logical Clock </blog/post/transactions-background-part-4-the-global-logical-clock>`.
109+
110+
* - ``$clusterTime``
111+
- Provides a document that returns the signed cluster time. Cluster time is a
112+
logical time used for ordering of operations.
113+
114+
The document contains the following fields:
115+
116+
- ``clusterTime``, which is the timestamp of the highest known cluster time for the member.
117+
- ``signature``, which is a document that contains the hash of the cluster time and the ID
118+
of the key used to sign the cluster time.
119+
120+
Example
121+
-------
122+
123+
The following example shows how to run the ``buildInfo`` command, and the output it produces:
124+
125+
.. io-code-block::
126+
127+
.. input:: /includes/run-command.kt
128+
:start-after: start-full-example
129+
:end-before: end-full-example
130+
:language: kotlin
131+
:dedent:
132+
133+
.. output::
134+
:visible: false
135+
136+
{
137+
version: '8.0.4',
138+
...<other command results>...
139+
ok: 1,
140+
'$clusterTime': {
141+
clusterTime: Timestamp({ ... }),
142+
signature: {
143+
...
144+
}
145+
},
146+
operationTime: Timestamp({ ... })
147+
}
148+
149+
150+
151+
.. _addl-info-runcommand:
152+
153+
Additional Information
154+
----------------------
155+
156+
For more information about the concepts in this guide, see the following documentation:
157+
158+
- `Kotlin Sync API runCommand() <{+api+}/com.mongodb.kotlin.client/-mongo-database/run-command.html>`__
159+
- :manual:`Database Commands </reference/command/>`
160+
- :manual:`explain Command </reference/command/explain/>`
161+
- :manual:`hello Command </reference/command/hello/>`
162+
- :manual:`buildInfo Command </reference/command/buildInfo/#mongodb-dbcommand-dbcmd.buildInfo>`

0 commit comments

Comments
 (0)