MongoDB\Driver\Command 类

(mongodb >=1.0.0)

简介

MongoDB\Driver\Command 类是一个值对象,表示数据库命令。

为了提供“命令助手”,应组合MongoDB\Driver\Command 对象。

类概要

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

示例

示例 #1 组合 MongoDB\Driver\Command 以提供创建集合的助手

<?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)
}

目录

添加备注

用户贡献的备注 4 则备注

tdrpic
8 年前
如果您想知道如何执行“distinct”查询

<?php

// MongoDB 命令示例:
// db.product.distinct("scent", {"prodCat": "10 oz can"})

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

$query = ['prodCat' => '10 oz can']; // 典型的 MongoDB 查询
$cmd = new MongoDB\Driver\Command([
// 构建 'distinct' 命令
'distinct' => 'product', // 指定集合名称
'key' => 'scent', // 指定要获取唯一值的字段
'query' => $query // 过滤文档的条件
]);
$cursor = $manager->executeCommand('catalog', $cmd); // 获取结果
$scents = current($cursor->toArray())->values; // 获取唯一值作为数组

var_dump($scents);

?>
jonny dot b dot 112 at gmail dot com
5 年前
0) 阅读官方 MongoDB 文档以了解可以使用哪些数据库命令以及它们需要哪些参数 - https://docs.mongodb.com/manual/reference/command/

1) 错误
$cmd = new \MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
因为 pipeline 是 JSON 中的对象数组(PHP 中的关联数组的索引数组) - pipeline: [ {<stage>}, ... ]
这意味着 'pipeline' 必须像这样
[
['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]], // 这是 {<stage>}
['$match' => [...]], // 还有这个
...
[...] // 以及所有这些
]
请查看 https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

2) 关联数组中用于 __construct 的参数 $document 的第一对(如果它是一个数组)必须是命令名称(例如 'count' => 'collectionName' 或 'findAndModify' => 'collectionName')。我通过实验发现了这一点,但是你可以检查源代码 https://github.com/mongodb/mongo-php-driver/blob/master/src/MongoDB/Command.c 了解为什么会出现这种情况。
532041020 at qq dot com
6 年前
错误
$cmd = new \MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
正确
$cmd = new \MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => [['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]][
]);
'pipeline' 缺少 '[]'
deiva at qq dot com
7 年前
我尝试在 PHP 5.7 中使用驱动程序 1.29 (https://pecl.php.net/package/mongodb/1.2.9),如下代码所示

$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);
}

有时会显示

致命错误:未捕获的异常“MongoDB\Driver\Exception\RuntimeException”,消息为“'pipeline' 必须指定为数组”

有时会显示

致命错误:未捕获的异常“MongoDB\Driver\Exception\ConnectionTimeoutException”,消息为“找不到合适的服务器(`serverSelectionTryOnce` 设置):[在 '127.0.0.1:27017' 上调用 ismaster 时套接字超时]”

PS:其他命令可以正常执行。
To Top