使用PHP7来批量更新MangoDB数据

直接贴代码

<?php

set_time_limit(0);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$namespace = 'test.test';
$aQuery = array('status' => 200);
$oQuery = new MongoDB\Driver\Query($aQuery);
$t1 = microtime(TRUE);
$cursor = $manager->executeQuery($namespace, $oQuery);
$i = 0;
$bulk = new MongoDB\Driver\BulkWrite;
foreach($cursor as $doc) {
    $i++;
    if ($i % 100000 === 0) {
        $manager->executeBulkWrite($namespace, $bulk);
        echo ($i / 10000) . 'W ' . number_format(microtime(TRUE) - $t1, 2) . " Seconds\r\n";
        $bulk = new MongoDB\Driver\BulkWrite;
    }
    $set = array();
    $set['A'] = strToArray($doc->a);
    $set['B'] = strToArray($doc->b);
    $set['C'] = strToArray($doc->c);
    $bulk->update(
        array('_id' => $doc->_id),
        array('$set' => $set)
    );
}
$manager->executeBulkWrite($namespace, $bulk);
echo 'Total: ' . number_format(microtime(TRUE) - $t1, 2) . " Seconds\r\n";

function strToArray($str) {
    $str = str_replace(',', ',', $str);
    $arr = explode(',', $str);
    $ret = array();
    foreach ($arr as $s) {
        $s = trim($s);
        if ($s) {
            $ret[] = $s;
        }
    }
    return $ret;
}

 

上一篇:七十二、MangoDB安装,基础连接和查询


下一篇:mangodb显示数据库数据