dongluan2612 2017-10-05 19:39 采纳率: 0%
浏览 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 :)

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

报告相同问题?