简体   繁体   English

MongoDB GridFS PHP附加文本

[英]MongoDB GridFS PHP append text

I'm trying to make a log system using mongodb in php and GridFS. 我正在尝试使用php和GridFS中的mongodb创建一个日志系统。 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 \n';
    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. 也尝试过在溪流旁fopen ,但没有运气。 I also don't know how to retrieve this file Id after writing data to it. 我还不知道在向其写入数据后如何检索此文件ID

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

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 :) 我只是切换到登录txt文件,而只是将对我的文件的引用存储在mongodb中更好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM