在 MongoDB 中存储大于 16 MB 的字符串(MongoDB 文档大小限制为 16 MB)

2023-12-24

Goal:

I want to store large encrypted strings into MongoDB. As I've learned from the PHP driver documentation it's only possible to store data larger than 16 MB when I'm using GridFS. The MongoDB PHP library doesn't offer a method to store "strings" in the grid. It just offers methods to store files (with a file path). Correct me if I'm wrong. If there is any method/function from the class to store a string larger than 16 MB into the database, please tell me.

编辑/答案:

将大于 16 MB 的字符串存储到 MongoDB 数据库

好吧,我终于弄清楚了,我很高兴它能工作!有一种方法可以保存strings with GridFS在数据库中。该文档不是很容易理解,我必须阅读每个的描述GridFS function多次了解每个内容function做了什么以及我可以通过它们每个人实现什么。

第一步:创建 MongoDB 驱动程序的 Client 类的实例

function __construct(){
        $client = new MongoDB\Client('mongodb://127.0.0.1/');
        $this->collection = $client->myExampleDatabase->myExampleCollection;
        $this->grid = $client->myExampleDatabase->selectGridFSBucket();
}

You do not必须使用__construct function!

因此,要存储大字符串,您必须执行以下操作:

function insertDocument($id, $telegramuser, $message, $hash, $file) {
        try {   
                $stream = fopen("php://temp", "w+b");
                fwrite($stream, $file);
                rewind($stream);
                $fileid = $this->grid->uploadFromStream("cryptedObject", $stream, array("metadata" => array()));
                $document = array(
                    "id" => $id,
                    "telegram" => $telegramuser,
                    "fileid" => $fileid,
                    "encrypted" => $message,
                    "hash" => $hash,
                    "timestamp" => time(),
                );
                $this->collection->insertOne($document);
        } catch(Exception $e) {
                echo "Error" . $e;
        }
}

我建议通过$fileid来自你的变量GridFSFile反对document,如上面的函数所示。存放的重要部件strings这些是:

$stream = fopen("php://temp", "w+b");
fwrite($stream, $file);
rewind($stream);
$fileid = $this->grid->uploadFromStream("cryptedObject", $stream, array("metadata" => array()));

$fileid包含自动地分配的id你的GridFSFile object你可以用它传递到另一个document作为你的参考GridFSFile object.

当您使用此函数时,您可以从数据库中检索字符串,并且可以将其回显或打印到屏幕上:

function getFile($id) {
        $document = $this->findDocument("id", $id);
        $fileid = $document->fileid;
        $stream = $this->grid->openDownloadStream($fileid);
        return stream_get_contents($stream);
}

首先,我从数据库中检索文档以获取fileid这是一个reference id to my GridFSFile object。然后我用openDownloadStream($fileid)创建一个resource in the variable $streamstream_get_contents($stream)我得到的内容resource $stream我可以用它来回显或打印屏幕上的内容,或者以我想要的任何方式使用它。

这就是整个魔法。

目前我无法推荐以下文档MongoDB,但要获得完整的答案,您可以找到GridFSPHP 文档here https://docs.mongodb.com/php-library/current/reference/class/MongoDBGridFSBucket/.


GridFS 支持任意数据 blob。数据库不关心(或不知道)存储的内容是否来自文件、网络流或其他来源,或者是简单的文本字符串。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 MongoDB 中存储大于 16 MB 的字符串(MongoDB 文档大小限制为 16 MB) 的相关文章

随机推荐