doujiang1939 2016-08-31 07:16
浏览 95
已采纳

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

I am using this

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

}

And the code works and getting output like bellow

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

Now I can't convert the object to array. How to get the properties like "nRemoved" / "nUpdated" from the object?

  • 写回答

1条回答 默认 最新

  • douyi1197 2017-02-17 10:29
    关注

    You can do it like this:

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

    To return deletes count:

    $result->getDeletedCount();

    More info about this methods here: http://php.net/manual/en/class.mongodb-driver-writeresult.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)