|
| 1 | +.. _javars-run-command: |
| 2 | + |
| 3 | +============ |
| 4 | +Run Commands |
| 5 | +============ |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +Not all database commands have a specific helper method. However, you can |
| 14 | +run any MongoDB command by using the ``MongoDatabase.runCommand()`` |
| 15 | +method. |
| 16 | + |
| 17 | +To learn more about MongoDB commands, see :manual:`Database Commands </reference/command/>` |
| 18 | +in the Server manual. |
| 19 | + |
| 20 | +Prerequisites |
| 21 | +------------- |
| 22 | + |
| 23 | +You must set up the following components to run the code examples in |
| 24 | +this guide: |
| 25 | + |
| 26 | +- A ``test.restaurants`` collection populated with documents from the |
| 27 | + ``restaurants.json`` file in the `documentation assets GitHub |
| 28 | + <https://raw.githubusercontent.com/mongodb/docs-assets/drivers/restaurants.json>`__. |
| 29 | + |
| 30 | +- The following import statements: |
| 31 | + |
| 32 | +.. code-block:: java |
| 33 | + |
| 34 | + import com.mongodb.reactivestreams.client.MongoClients; |
| 35 | + import com.mongodb.reactivestreams.client.MongoClient; |
| 36 | + import com.mongodb.reactivestreams.client.MongoDatabase; |
| 37 | + import org.bson.Document; |
| 38 | + |
| 39 | +.. important:: |
| 40 | + |
| 41 | + This guide uses the ``Subscriber`` implementations, which are |
| 42 | + described in the :ref:`Quick Start Primer <javars-primer>`. |
| 43 | + |
| 44 | +Connect to a MongoDB Deployment |
| 45 | +------------------------------- |
| 46 | + |
| 47 | +First, connect to a MongoDB deployment, then declare and define |
| 48 | +a ``MongoDatabase`` instance. |
| 49 | + |
| 50 | +The following code connects to a standalone |
| 51 | +MongoDB deployment running on ``localhost`` on port ``27017``. Then, it |
| 52 | +defines the ``database`` variable to refer to the ``test`` database: |
| 53 | + |
| 54 | +.. code-block:: java |
| 55 | + |
| 56 | + MongoClient mongoClient = MongoClients.create(); |
| 57 | + MongoDatabase database = mongoClient.getDatabase("test"); |
| 58 | + |
| 59 | +To learn more about connecting to MongoDB deployments, |
| 60 | +see the :ref:`javars-connect` tutorial. |
| 61 | + |
| 62 | +Run the buildInfo Command |
| 63 | +------------------------- |
| 64 | + |
| 65 | +To run the ``buildInfo`` command, construct a ``Document`` object that |
| 66 | +specifies the command and pass it as a paramter to the ``runCommand()`` method. |
| 67 | + |
| 68 | +The following sample code runs the ``buildInfo`` command and prints |
| 69 | +the results: |
| 70 | + |
| 71 | +.. code-block:: java |
| 72 | + |
| 73 | + database.runCommand(new Document("buildInfo", 1)).subscribe(new PrintDocumentSubscriber()); |
0 commit comments