![](/img/trans.png)
[英]Using php, how to save a smaller than 16mb images in mongoDB using BSON
[英]Storing strings larger than 16 MB in MongoDB (MongoDB document size limit is 16 MB)
我想将大型加密strings
存储到MongoDB
中。 正如我从 PHP 驱动程序文档中了解到的那样,当我使用GridFS
时,只能存储大于 16 MB 的数据。 MongoDB PHP 库不提供在网格中存储“字符串”的方法。 它只是提供了存储文件的方法(带有文件路径)。 如我错了请纠正我。 如果class
有任何方法/功能可以将大于 16 MB 的string
存储到数据库中,请告诉我。
好的,我终于想通了,我很高兴它起作用了! 有一种方法可以在数据库中使用GridFS
存储strings
。 文档不是很容易理解,我不得不多次阅读每个GridFS
function
的描述,以了解每个function
的作用以及我可以用它们实现什么。
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
object 传递到document
,如上面的 function 所示。 存储strings
的重要部分是:
$stream = fopen("php://temp", "w+b");
fwrite($stream, $file);
rewind($stream);
$fileid = $this->grid->uploadFromStream("cryptedObject", $stream, array("metadata" => array()));
$fileid
包含自动分配的GridFSFile object
的id
,您可以使用它作为对GridFSFile object
的引用传递到另一个document
中。
function getFile($id) {
$document = $this->findDocument("id", $id);
$fileid = $document->fileid;
$stream = $this->grid->openDownloadStream($fileid);
return stream_get_contents($stream);
}
首先,我从数据库中检索文档以获取fileid
,它是我的GridFSFile object
的reference id
。 然后我使用openDownloadStream($fileid)
在variable
$stream
中创建一个resource
,并使用stream_get_contents($stream)
我得到resource
$stream
的内容,我可以使用它在屏幕上回显或打印内容,或者使用它以我想要的任何方式。
这就是全部的魔法。
目前我不能推荐MongoDB
的文档,但要获得完整的答案,您可以在此处找到GridFS
PHP 文档。
GridFS 支持任意数据块。 数据库不关心(或知道)存储的内容是来自文件还是来自网络 stream 或其他来源,还是简单的文本字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.