代码之家  ›  专栏  ›  技术社区  ›  Hirad Roshandel

MongoDB GridFS PHP追加文本

  •  1
  • Hirad Roshandel  · 技术社区  · 8 年前

    我正在尝试使用 mongodb in php 和GridFS。我最初可以将数据写入文件,但一旦关闭流,我就不知道以后如何将数据追加到其中。我是这样写的:

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

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

    fopen 在溪流上,但没有运气。我也不知道怎么取回这个 文件Id

    1 回复  |  直到 8 年前
        1
  •  0
  •   Hirad Roshandel    7 年前

    我找不到一个简单的附加解决方案,所以我最终用一个新文件替换了以前的文件,并删除了旧文件。

    $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."\n"; // 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();
    

    更新:

    推荐文章