php - 在 MongoDB 中存储大于 16 MB 的字符串(MongoDB 文档大小限制为 16 MB)
问题描述
目标:
我想将大加密存储strings
到MongoDB
. 正如我从 PHP 驱动程序文档中了解到的那样,当我使用GridFS
. MongoDB PHP 库不提供在网格中存储“字符串”的方法。它只是提供了存储文件的方法(带有文件路径)。如我错了请纠正我。如果有任何方法/功能class
可以将string
大于 16 MB 的数据存储到数据库中,请告诉我。
编辑/回答:
将大于 16 MB 的字符串存储到 MongoDB 数据库
好的,我终于想通了,我很高兴它起作用了!有一种方法可以存储strings
在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();
}
您不必使用__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
包含您的自动分配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
的GridFSFile object
. 然后,我使用openDownloadStream($fileid)
在其中创建一个resource
,variable
$stream
并stream_get_contents($stream)
获得resource
$stream
可用于在屏幕上回显或打印内容的内容,或以任何我想要的方式使用它。
这就是全部的魔法。
目前我无法推荐 的文档MongoDB
,但要获得完整的答案,您可以在此处GridFS
找到PHP 文档。
解决方案
GridFS 支持任意数据块。数据库不关心(或知道)存储的内容是来自文件还是来自网络流或其他来源,或者是简单的文本字符串。
推荐阅读
- javascript - 我想创建选项卡以更改 div 中的月份名称 - 附加图像
- javascript - Moment.js - 不同设备上的日期不一致
- python - 如何从嵌套列表中找到第 k 个最大的子列表(按长度)
- xaml - 在条目 xamarin.forms 的焦点和非焦点上设置动画标签
- strapi - 尝试在 Strapi CMS 的 Quill 编辑器插件中使用 peaks.js。得到:ReferenceError:导航器未定义
- java - 在 java 中查询 AWS lambda 函数
- react-native - 如何以编程方式打开/关闭 react-native-calendars 的 ExpandableCalendar?
- android - 如何在 Play 商店中为 Android 产品包实现应用内更新
- javascript - 如何居中对齐?
- flutter - 如何创建混合路线,如(行人和汽车)?