MongoDBDatabase-command.txt 2.46 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
============================
MongoDB\\Database::command()
============================

.. default-domain:: mongodb

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

Definition
----------

.. phpmethod:: MongoDB\\Database::command

   Execute a :manual:`command </reference/command>` on the database.
   
   .. code-block:: php
                   
      function command($command, array $options = []): MongoDB\Driver\Cursor

   :phpmethod:`MongoDB\\Database::command` has the following parameters:

   .. include:: /includes/apiargs/MongoDBDatabase-method-command-param.rst
   
   ``command`` supports the following options:
   
   .. include:: /includes/apiargs/MongoDBDatabase-method-command-option.rst

Example
-------

The following operation creates a new user in the database using
the :dbcommand:`createUser` command:

.. code-block:: php

   $database = (new MongoDB\Client)->example;

   $newUser = $database->command(
       [
           'createUser' => 'admin',
           'pwd' => 'admin123',
           'roles' => [
               'readWrite'
           ]
       ]
   );

   

   var_dump($newUser);

The output would resemble::
  
  object(MongoDB\Driver\Cursor)#10 (2) {
     ["cursor"]=>
     array(17) {
       ["stamp"]=>
       int(0)
       ["is_command"]=>
       bool(true)
       ["sent"]=>
       bool(true)
       ["done"]=>
       bool(false)
       ["end_of_event"]=>
       bool(false)
       ["in_exhaust"]=>
       bool(false)
       ["has_fields"]=>
       bool(false)
       ["query"]=>
       object(stdClass)#9 (3) {
         ["createUser"]=>
         string(5) "admin"
         ["pwd"]=>
         string(8) "admin123"
         ["roles"]=>
         array(1) {
           [0]=>
           string(9) "readWrite"
         }
       }
       ["fields"]=>
       object(stdClass)#3 (0) {
       }
       ["read_preference"]=>
       array(2) {
         ["mode"]=>
         int(1)
         ["tags"]=>
         array(0) {
         }
       }
       ["flags"]=>
       int(0)
       ["skip"]=>
       int(0)
       ["limit"]=>
       int(1)
       ["count"]=>
       int(1)
       ["batch_size"]=>
       int(0)
       ["ns"]=>
       string(12) "example.$cmd"
       ["current_doc"]=>
       object(stdClass)#8 (1) {
         ["ok"]=>
         float(1)
       }
     }
     ["server_id"]=>
     int(1)
   }

.. seealso::
   
   - :doc:`/tutorial/commands`
   - :manual:`Database Commands </reference/command>` in the
     MongoDB manual