MongoDB GridFS PHP 追加文本

MongoDB GridFS PHP append text

我正在尝试使用 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

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

$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();

更新: 对于未来的读者,在使用这个系统几个月后,我意识到这不是一个好的解决方案。文件和块可能会损坏,而且这个过程非常慢。我只是切换到登录 txt 文件并将对我的文件的引用存储在 mongodb 中更好:)