代码之家  ›  专栏  ›  技术社区  ›  Roman

php mongodb异常:未授权db执行命令{update:

  •  0
  • Roman  · 技术社区  · 7 年前

    我有以下代码

    $bulkWrite=new MongoDB\Driver\BulkWrite;
    $filter = ['name' => 'John'];
    $update = ['$set' => ['name' => 'Smith', age: 35, profession => 'pilot']];
    $options = array('multi' => false, 'upsert' => false);
    $bulkWrite->update($filter, $options);
    $mongoConn->executeBulkWrite('MyCollection', $bulkWrite);
    

    代码返回错误:

    Exception:not authorized on db to execute command { update:
    

    怎么了?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Roman    7 年前

    在检查代码后,我发现问题出在集合的名称中。
    如果我们以前有过:

    $DB_CONNECTION_STRING="mongodb://dbName:dbPassword";
    require '../../vendor/autoload.php';
    $mongoConn = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
    

    然后在需要正确引用dbname之后:

    $bulkWrite=new MongoDB\Driver\BulkWrite;
    $filter = ['name' => 'John'];
    $update = ['$set' => ['name' => 'Smith', age: 35, profession => 'pilot']];
    $options = array('multi' => false, 'upsert' => false);
    $bulkWrite->update($filter, $options);
    $mongoConn->executeBulkWrite('dbName.MyCollection', $bulkWrite);