dongluan2612 2017-10-05 19:39
浏览 142
已采纳

MongoDB GridFS PHP附加文本

I'm trying to make a log system using mongodb in php and GridFS. I can initially write data to my file but once I close the stream I don't know how to append data later to it. This is how I write to it:

    $bucket= DB::connection('mongodb')->getMongoDB()->selectGridFSBucket();
    $stream = $bucket->openUploadStream('my-file-name.txt');
    $contents = 'whatever text here 
';
    fwrite($stream, $contents);
    fclose($stream);

I tried retreiving it and appending data to the stream but it doesn't work. This is attempt:

    $bucket= DB::connection('mongodb')->getMongoDB()->selectGridFSBucket();
    $stream = $bucket->openDownloadStreamByName('my-file-name.txt');
    fwrite($stream, $contents);

also tried fopen on the stream but no luck. I also don't know how to retrieve this file Id after writing data to it.

  • 写回答

1条回答 默认 最新

  • drxp993551 2017-10-06 14:35
    关注

    I couldn't find a simple solution to append so I ended up replacing the previous file with a new file and deleting the old one.

    $stream = $bucket->openDownloadStream($this->file_id);
    $prev_content = stream_get_contents($stream);
    
    //delete old data chunks
    DB::connection('mongodb')->collection('fs.chunks')->where('files_id',$this->file_id)->delete();
    //delete old file
    DB::connection('mongodb')->collection('fs.files')->where('_id',$this->file_id)->delete();
    
    
    $new_content =$prev_content.$dt.$msg."
    "; // append to log body
    $new_filename = $filename_prefix;
    $stream = $bucket->openUploadStream($new_filename);
    fwrite($stream, $new_content);
    fclose($stream);
    
    $new_file = DB::connection('mongodb')->collection('fs.files')->where('filename',$new_filename)->first();
    

    UPDATE: For future readers, after using this system for few months I realized this is not a good solution. Files & chunks can get corrupted and also the process is super slow. I simply switched to logging in a txt file and just storing a reference to my file in mongodb much better :)

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

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效