首页 > 解决方案 > 在 MongoDB 中存储大于 16 MB 的字符串(MongoDB 文档大小限制为 16 MB)

问题描述

目标:

我想将大加密存储stringsMongoDB. 正如我从 PHP 驱动程序文档中了解到的那样,当我使用GridFS. MongoDB PHP 库不提供在网格中存储“字符串”的方法。它只是提供了存储文件的方法(带有文件路径)。如我错了请纠正我。如果有任何方法/功能class可以将string大于 16 MB 的数据存储到数据库中,请告诉我。

编辑/回答:

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

好的,我终于想通了,我很高兴它起作用了!有一种方法可以存储stringsGridFS数据库中。文档不是很容易理解,我不得不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();
}

不必使用__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对象传递给 a document,就像上面的函数一样。存储的重要部分strings是:

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

$fileid包含您的自动分配idGridFSFile 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);
}

首先,我从数据库中检索文档以获取fileidreference idGridFSFile object. 然后,我使用openDownloadStream($fileid)在其中创建一个resourcevariable $streamstream_get_contents($stream)获得resource $stream可用于在屏幕上回显或打印内容的内容,或以任何我想要的方式使用它。

这就是全部的魔法。

目前我无法推荐 的文档MongoDB,但要获得完整的答案,您可以在此处GridFS找到PHP 文档。

标签: phpmongodb

解决方案


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


推荐阅读