【问题标题】:PHP MongoDB insert using loopPHP MongoDB 使用循环插入
【发布时间】:2015-07-29 21:41:55
【问题描述】:

我目前在 PHP 中使用 MongoDB 时遇到了一些问题。

我正在从 CSV 文件中提取财务数据记录,几乎是一次演出,我正在循环遍历文件并输出和解析数组。

在 while 循环期间,我还尝试将数据插入到 MongoDB 中

// Increase timeout on php script
ini_set('max_execution_time', 600);

while (($data = fgetcsv($file, 0, ",")) !==FALSE) {

    $parsedData['name'] = $data['0'];
    $parsedData['email'] = $data['1'];
    $parsedData['phone'] = $data['2'];
    $parsedData['address'] = $data['3'];
    $parsedData['gender'] = $data['4'];

    $collection->insert($parsedData);

}

所以问题是它只插入了一条或几条记录,我真的不能说它看起来很随机。

这里的任何帮助都会很棒。

测试完成

  • 在使用 mysql 测试时运行相同的函数返回成功。
  • print_r($parsedData) 显示所需的值。
  • 包装 $collection->insert 在 if 语句中返回 true

【问题讨论】:

  • 什么是$parsedData
  • 你是从命令行运行这个吗?因为根据您的服务器,通常会有 30 秒的超时。
  • 我正在卷曲这个并且在模型的顶部也有以下内容 ini_set('max_execution_time', 600);
  • @Livewire 更新超时秒数,即使超时我应该在数据库中获得不止一条记录?
  • 什么都没看到,只能猜测数据文件有坏的换行符或者PHP函数fgetcsv()无法解析的换行符。

标签: php mongodb


【解决方案1】:

好的,在阅读了一些 MongoDB 文档的更多内容后,我设法解决了这个问题。

  1. 我用 try and catch 添加了一个异常包装了这个过程
  2. 为发送到 MongoDB 的数组添加了 fsync 和安全
  3. 最后添加的部分是“new MongoId”,因为 MongoDB 返回重复的 _id(据我所知,这是唯一必要的步骤)

    while (($data = fgetcsv($file, 0, ",")) !==FALSE) {
        try{ 
    
            // Add MongoId, without this it was returning a duplicate key 
            // error in the catch.
            $parsedData['_id'] =  new MongoId();
    
            $parsedData['name'] = $data['0'];
            $parsedData['email'] = $data['1'];
            $parsedData['phone'] = $data['2'];
            $parsedData['address'] = $data['3'];
            $parsedData['gender'] = $data['4'];
    
            // Submitted "safe" and "fsync" with the array, as far as I
            // can see MongoDB waits till data is entered before it sends
            // a true response instead of continuing after the function is 
            // executed.
            $collection->save($parsedData, array('safe' => true, 'fsync' => true));
    
    
        }catch(MongoCursorException $e){
            // This is where I caught the duplicate id
            print_r($e->doc['err']);
    
            // Kill the procedure
            die();
        }
    }
    

如果有人可以添加它,那就太好了,因为我认为 Mongo 生成了自己的 id,并且它只会在输入数据时返回 true,或者我只是希望它运行类似于 MySQL 驱动程序。

【讨论】:

  • 当有人找到自己的答案为他人的利益发布它时,我总是很感激。很高兴了解 Mongo 和 MySQL 在唯一 ID 方面的区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2012-04-23
  • 2019-01-21
  • 2016-03-27
相关资源
最近更新 更多