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

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

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流