Skip to content

Commit 2cacc69

Browse files
authored
DOCSP-18237: run a command (#176)
* DOCSP-18237: run a command page * first pass fixes * changed examples * MW PR fixes 1 * small fixes * link to logical clock ref
1 parent 97607a1 commit 2cacc69

File tree

3 files changed

+220
-1
lines changed

3 files changed

+220
-1
lines changed

source/fundamentals/crud.txt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ CRUD Operations
1212
/fundamentals/crud/read-operations
1313
/fundamentals/crud/write-operations
1414
/fundamentals/crud/compound-operations
15-
/fundamentals/crud/write-read-pref.txt
15+
/fundamentals/crud/run-command
16+
/fundamentals/crud/write-read-pref
1617

1718
CRUD (Create, Read, Update, Delete) operations enable you to work with
1819
data stored in MongoDB.
@@ -25,4 +26,6 @@ data stored in MongoDB.
2526
Some operations combine aspects of read and write operations. To learn
2627
more about these hybrid methods, see :ref:`golang-compound-operations`.
2728

29+
To run a raw database operation, see :ref:`golang-run-command`.
30+
2831
To learn about how to modify the way your CRUD operations execute, see :ref:`golang-write-read-pref`.
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
.. _golang-run-command:
2+
3+
=============
4+
Run a Command
5+
=============
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 1
13+
:class: singlecol
14+
15+
Overview
16+
--------
17+
18+
In this guide, you can learn how to run a **database command** with the
19+
{+driver-short+}. You can use database commands to perform a variety of
20+
administrative and diagnostic tasks, such as fetching server statistics,
21+
initializing a replica set, or running an aggregation pipeline.
22+
23+
Compose a Command
24+
-----------------
25+
26+
The {+driver-short+} provides the following methods to run database
27+
commands:
28+
29+
- ``RunCommand()``, which returns the command response as a
30+
``SingleResult`` type. You can use this method with any database command.
31+
- ``RunCommandCursor()``, which returns the command response as a
32+
``Cursor`` type. You can use this method if your database command
33+
returns multiple result documents.
34+
35+
Each method requires a Context and a command document. The
36+
command document must be an order-preserving type such as ``bson.D``.
37+
The following code shows how you can use the ``RunCommandCursor()``
38+
method to run the ``listCollections`` command on a database:
39+
40+
.. code-block:: go
41+
42+
command := bson.D{{"listCollections", 1}}
43+
cursor, err := db.RunCommandCursor(context.TODO(), command)
44+
45+
For a full list of database commands, see the :ref:`Additional
46+
Information <addl-info-runcommand>`.
47+
48+
.. note:: Read Preference
49+
50+
``RunCommand()`` and ``RunCommandCursor()`` do not obey the read
51+
preference set for the database. You can set a read preference for a
52+
database command by passing a ``RunCmdOptions`` type to either method:
53+
54+
.. code-block:: go
55+
56+
opts := options.RunCmd().SetReadPreference(readpref.Primary())
57+
err := db.RunCommand(context.TODO(), command, opts).Decode(&result)
58+
59+
For more information on
60+
read preference options, see the :ref:`golang-write-read-pref`
61+
fundamentals page.
62+
63+
Response
64+
--------
65+
66+
Each method returns a document or a cursor containing documents with the
67+
following fields:
68+
69+
.. list-table::
70+
:header-rows: 1
71+
:widths: 30 70
72+
73+
* - Field
74+
- Description
75+
76+
* - <command result>
77+
- Provides fields specific to the database command. For example,
78+
``count`` returns the ``n`` field and ``explain`` returns the
79+
``queryPlanner`` field.
80+
81+
* - ``ok``
82+
- Indicates whether the command has succeeded (``1``)
83+
or failed (``0``).
84+
85+
* - ``operationTime``
86+
- Indicates the :website:`logical time
87+
</blog/post/transactions-background-part-4-the-global-logical-clock>`
88+
of the operation. MongoDB uses the logical time to order operations.
89+
90+
* - ``$clusterTime``
91+
- Provides a document that returns the signed cluster time. Cluster time is a
92+
logical time used for ordering of operations.
93+
94+
The document contains the following fields:
95+
96+
- ``clusterTime``, which is the timestamp of the highest known cluster time for the member.
97+
- ``signature``, which is a document that contains the hash of the cluster time and the ID
98+
of the key used to sign the cluster time.
99+
100+
Example
101+
-------
102+
103+
The following code shows how you can use the ``RunCommand()`` method to
104+
run the ``count`` command on the ``flowers`` collection of the
105+
``plants`` database. This example searches for documents with a
106+
``price`` property less than or equal to 9.99.
107+
108+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/runCommand.go
109+
:language: go
110+
:dedent:
111+
:start-after: start-runcommand
112+
:end-before: end-runcommand
113+
114+
Output
115+
~~~~~~
116+
117+
In the output, you should see the number of documents in
118+
the collection that match the query as the value of the ``n`` field, as
119+
well as the command execution information:
120+
121+
.. code-block:: json
122+
:emphasize-lines: 15
123+
124+
{
125+
"$clusterTime": {
126+
"clusterTime": {
127+
"T": 1666967516,
128+
"I": 32
129+
},
130+
"signature": {
131+
"hash": {
132+
"Subtype": 0,
133+
"Data": "..."
134+
},
135+
"keyId": 7120249010111119362
136+
}
137+
},
138+
"n": 47,
139+
"ok": 1,
140+
"operationTime": {
141+
"T": 1666967516,
142+
"I": 32
143+
}
144+
}
145+
146+
.. _addl-info-runcommand:
147+
148+
Additional Information
149+
----------------------
150+
151+
For more information about the concepts in this guide, see the following documentation:
152+
153+
- :manual:`db.runCommand() </reference/method/db.runCommand/>`
154+
- :manual:`Database Commands </reference/command/>`
155+
- :manual:`listCollections Command </reference/command/listCollections/>`
156+
- :manual:`count Command </reference/command/count/>`
157+
158+
To learn how to retrieve data from a cursor, see the
159+
:ref:`golang-cursor` fundamentals page.
160+
161+
API Documentation
162+
~~~~~~~~~~~~~~~~~
163+
164+
- `RunCommand() <{+api+}/mongo#Database.RunCommand>`__
165+
- `RunCommandCursor() <{+api+}/mongo#Database.RunCommandCursor>`__
166+
- `RunCmdOptions <{+api+}/mongo/options#RunCmdOptions>`__
167+
- `Cursor <{+api+}/mongo#Cursor>`__
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"log"
8+
"os"
9+
10+
"go.mongodb.org/mongo-driver/bson"
11+
"go.mongodb.org/mongo-driver/mongo"
12+
"go.mongodb.org/mongo-driver/mongo/options"
13+
)
14+
15+
func main() {
16+
17+
var uri string
18+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
19+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
20+
}
21+
22+
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
23+
if err != nil {
24+
panic(err)
25+
}
26+
defer func() {
27+
if err = client.Disconnect(context.TODO()); err != nil {
28+
panic(err)
29+
}
30+
}()
31+
32+
// start-runcommand
33+
db := client.Database("plants")
34+
filter := bson.D{{"price", bson.D{{"$lte", 9.99}}}}
35+
command := bson.D{{"count", "flowers"}, {"query", filter}}
36+
37+
var result bson.M
38+
err = db.RunCommand(context.TODO(), command).Decode(&result)
39+
// end-runcommand
40+
41+
if err != nil {
42+
panic(err)
43+
}
44+
output, err := json.MarshalIndent(result, "", " ")
45+
if err != nil {
46+
panic(err)
47+
}
48+
fmt.Printf("%s\n", output)
49+
}

0 commit comments

Comments
 (0)