如何在php中获取MongDB更新/删除操作的状态?

时间:2016-08-31 07:16:59

标签: php arrays mongodb

我正在使用此

function delete($col,$condition = array()){
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->delete($condition, ['limit' => 1]);

    $manager = new MongoDB\Driver\Manager($this->mongo);
    $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
    $result = $manager->executeBulkWrite($this->db.'.'.$col, $bulk, $writeConcern);
    var_dump($result);

}

代码可以正常运行并获得输出

  

object(MongoDB \ Driver \ WriteResult)#30(9){[“nInserted”] => int(0)[“nMatched”] => int(0)[“nModified”] => int(0)[“nRemoved”] => int(0)[“nUpserted”] => int(0)[“upsertedIds”] => array(0){} [“writeErrors”] => array(0){} [“writeConcernError”] => NULL [“writeConcern”] => array(4){[“w”] => string(8)“majority”[“wmajority”] => bool(true)[“wtimeout”] => int(1000)[“journal”] => NULL}}

现在我无法将对象转换为数组。如何从对象中获取“nRemoved”/“nUpdated”等属性?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->update(
    $condition,
    $data,
    $n_opts
);
if($result = $this->mongo->executeBulkWrite($this->db.'.'.$collection, $bulk)){
    if(($result->getMatchedCount() > 0 AND $result->getModifiedCount() > 0) OR ($result->getMatchedCount() == 0 AND $result->getUpsertedCount() > 0)){
        return true;
    }else{
        return false;
    }
}else{
    return false;
}

要返回删除计数:

$ result-> getDeletedCount();

此处有关此方法的更多信息: http://php.net/manual/en/class.mongodb-driver-writeresult.php