The MongoDB\Driver\Command class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide Command Helpers the MongoDB\Driver\Command object should be composed.

类摘要

final MongoDB\Driver\Command {
/* 方法 */
final public __construct ( array|object $document , array $commandOptions = ? )
}

范例

Example #1 Composing MongoDB\Driver\Command to provide a helper to create collections

<?php
class CreateCollection {
    protected 
$cmd = array();

    function 
__construct($collectionName) {
        
$this->cmd["create"] = (string)$collectionName;
    }
    function 
setCappedCollection($maxBytes$maxDocuments false) {
        
$this->cmd["capped"] = true;
        
$this->cmd["size"]   = (int)$maxBytes;

        if (
$maxDocuments) {
            
$this->cmd["max"] = (int)$maxDocuments;
        }
    }
    function 
usePowerOf2Sizes($bool) {
        if (
$bool) {
            
$this->cmd["flags"] = 1;
        } else {
            
$this->cmd["flags"] = 0;
        }
    }
    function 
setFlags($flags) {
        
$this->cmd["flags"] = (int)$flags;
    }
    function 
getCommand() {
        return new 
MongoDB\Driver\Command($this->cmd);
    }
    function 
getCollectionName() {
        return 
$this->cmd["create"];
    }
}


$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 1024);

try {
    
$command $createCollection->getCommand();
    
$cursor $manager->executeCommand("databaseName"$command);
    
$response $cursor->toArray()[0];
    
var_dump($response);

    
$collstats = ["collstats" => $createCollection->getCollectionName()];
    
$cursor $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
    
$response $cursor->toArray()[0];
    
var_dump($response);
} catch(
MongoDB\Driver\Exception $e) {
    echo 
$e->getMessage(), "\n";
    exit;
}

?>

以上例程会输出:

object(MongoDB\Driver\Command)#3 (1) {
  ["command"]=>
  array(3) {
    ["create"]=>
    string(16) "cappedCollection"
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(65536)
  }
}
array(1) {
  ["ok"]=>
  float(1)
}
array(16) {
  ["ns"]=>
  string(29) "databaseName.cappedCollection"
  ["count"]=>
  int(0)
  ["size"]=>
  int(0)
  ["numExtents"]=>
  int(1)
  ["storageSize"]=>
  int(65536)
  ["nindexes"]=>
  int(1)
  ["lastExtentSize"]=>
  float(65536)
  ["paddingFactor"]=>
  float(1)
  ["paddingFactorNote"]=>
  string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
  ["userFlags"]=>
  int(0)
  ["capped"]=>
  bool(true)
  ["max"]=>
  int(9223372036854775807)
  ["maxSize"]=>
  int(65536)
  ["totalIndexSize"]=>
  int(8176)
  ["indexSizes"]=>
  object(stdClass)#4 (1) {
    ["_id_"]=>
    int(8176)
  }
  ["ok"]=>
  float(1)
}

Table of Contents

User Contributed Notes

jonny dot b dot 112 at gmail dot com 27-Sep-2018 09:14
0) Read the official MongoDB documentation for understand what db commands you can use and what parameters they requires - https://docs.mongodb.com/manual/reference/command/

1) Wrong:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
because pipeline is array of objects in json words (index array of associative arrays in php words) - pipeline: [ {<stage>}, ... ]
What does it mean? It means that  'pipeline' must be like this:
[
    ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]],    // this is {<stage>}
    ['$match' => [...]],    // and this
    ...
    [...]    // and all of that
]
Just see https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

2) The first pair in associative array for __construct's argument $document (if it is an array) must be a command name (e. g. 'count' => 'collectionName' or 'findAndModify' => 'collectionName'). I found this out experimentally, but you can examine source code  https://github.com/mongodb/mongo-php-driver/blob/master/src/MongoDB/Command.c for understand why it happens.
532041020 at qq dot com 30-Sep-2017 02:33
Wrong:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
Right:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => [['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]][
]);
The 'pipeline' lack of '[]'
deiva at qq dot com 11-Aug-2017 09:59
I try to use the driver 1.29 (https://pecl.php.net/package/mongodb/1.2.9) in PHP 5.7, as following codes:

$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');

$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);

$rows = $mongo->executeCommand('database',  $cmd);
foreach($rows as $r){
    print_r($r);
}

it sometime saids:

Fatal error: Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' with message ''pipeline' must be specified as an array'

sometime as :

Fatal error: Uncaught exception 'MongoDB\Driver\Exception\ConnectionTimeoutException' with message 'No suitable servers found (`serverSelectionTryOnce` set): [socket timeout calling ismaster on '127.0.0.1:27017']'

PS: other command can be executed normally.
tdrpic 09-Aug-2016 05:28
In case you're wondering how to perform a 'distinct' query:

<?php

// Sample MongoDB command:
// db.product.distinct("scent", {"prodCat": "10 oz can"})

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$query = ['prodCat' => '10 oz can']; // your typical MongoDB query
$cmd = new MongoDB\Driver\Command([
   
// build the 'distinct' command
   
'distinct' => 'product', // specify the collection name
   
'key' => 'scent', // specify the field for which we want to get the distinct values
   
'query' => $query // criteria to filter documents
]);
$cursor = $manager->executeCommand('catalog', $cmd); // retrieve the results
$scents = current($cursor->toArray())->values; // get the distinct values as an array

var_dump($scents);

?>