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
$stream
与stream_get_contents($stream)
我得到的内容resource
$stream
我可以用它来回显或打印屏幕上的内容,或者以我想要的任何方式使用它。
这就是整个魔法。
目前我无法推荐以下文档MongoDB
,但要获得完整的答案,您可以找到GridFS
PHP 文档here https://docs.mongodb.com/php-library/current/reference/class/MongoDBGridFSBucket/.