I am a Java developer (am not familiar with PHP; I think you are using MongoDB PHP driver). I tried your issue of storing a string into GridFS collections. It works both ways, writing a string and retrieving it. Ofcourse, I used Java APIs. I can relate to what I did (code) in PHP, and I think a PHP developer can figure the rest.
Writing to GridFS:
Start from this topic: Uploading Files with Writable Streams
See the bucket class function: MongoDB\GridFS\Bucket::uploadFromStream
The function definition:
uploadFromStream($filename, $source, array $options = )
$filename: This can be any name (a string value) for identifying - this is stored as
filename field in the resulting
$source: Readable stream, from which the new GridFS file’s contents will be read.
The Readable stream is an input stream which is created from the input string; and this needs to be created in PHP code (
$streamToUploadFrom). With Java, the stream is created as:
InputStream streamToUploadFrom = new ByteArrayInputStream(inputString.getBytes("UTF-8"));
Write the string to the MongoDB GridFS collections:
$bucket = (new MongoDB\Client)->test->selectGridFSBucket();
The function returns: The
_id field of the metadata document associated with the newly created GridFS file.
After the successful write, MongoDB creates two collections in the specified database:
fs.files. These collections can be queried from the
mongo shell or from the driver APIs.
Reading from GridFS:
To read from the GridFS collection, use
MongoDB\GridFS\Bucket::downloadToStream function. In this case, an output steam is to be created and the
downloadToStream function reads from the stored string to the stream. Then, extract the string from the stream.