From f2a1dff4abe5517e529e5794e216a6d79e779090 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 10 Sep 2024 15:32:14 -0400 Subject: [PATCH 01/16] DOCSP-41972: GridFS guide --- source/includes/figures/GridFS-upload.png | Bin 0 -> 9225 bytes source/includes/write/gridfs.php | 63 +++++ source/write.txt | 1 + source/write/gridfs.txt | 280 ++++++++++++++++++++++ 4 files changed, 344 insertions(+) create mode 100644 source/includes/figures/GridFS-upload.png create mode 100644 source/includes/write/gridfs.php create mode 100644 source/write/gridfs.txt diff --git a/source/includes/figures/GridFS-upload.png b/source/includes/figures/GridFS-upload.png new file mode 100644 index 0000000000000000000000000000000000000000..2207752bc6f9010ed0117b9d2fe7e92c97e5f3ea GIT binary patch literal 9225 zcmbt)hgTC_(6A9f}11%@*l`B^mo<7kszH;R% z?8+4ii)&Xe5%Fs?X_wPA=tF~tSFTjV(4E>*Uh4mN8S7|XK@W1TUMlR*^-UjNTwJgg zo65<_jn86L?agyq%3xu^7A;{_@9sNYxx#zpsn$bN#555#W4hFVImeKJ{Hm46vOP+sjCi2DR)5YWo_c{SJT`wKo=^+ z?@{A_EMX?S?0-gl^Up-}+a`4^tg)px)4^1;XD&oB7F4NO7e~dZZ`X%@sWX*bv1eQT zp|oB^s+S_xGr0je%Oa8v1@Vkej@rFFzcLd`sC`Lug#mTNZFlqye0A5W9fcT;QXGWR zJW$XS|1|(6yWx74SUzvxrRS0*V6@Bi(=AgbZSUFMb?@prjUj#5nc8D<;@5B5xK4ew zEnRFyI4WVX&_SF&PfR`=|K{(PDo^6LeGVI4pG{-K7v(dnTk6RuC?wLO-*7bwrH7lo zCC62ki2sbsD^G+i%eJYxQ31l@EuKW;LK;-fNZ|43Dsncxm@KB!uamoaof$*j;5%-K z;t-OWr2x)b`iS@1ik`sV^nO8-hM&=Za&d*b^$cDy@nw%#^E~7006vWLC|nsf%3r;k z@Sqnf5;CO*>GrKCW6$ox8%OGb_KGmuRv)D(5ml*am0ln4?;m|A&k$p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`2Y_3!_P zgG1rJ&;xU&!8d$95z)-XvW>-=c#cZf2)Ju@uVnUCSceX-;yXW@6dZzzSzfxwFWso>{2D9!1Ud>NIA0%}Wj&nJyPSKFP|DY5)0( z@zp(E%%eZg_QnsmV!{3oVZRu8f#-riwadl^UmV!KitgP_tKKhO9}oPcH-U}hVqt582K92N{;9;T-{?x6e@ZhbH?57+2U0RJJBJOwYij5?^TIS+^ zV-y=D?q?M9iE$8Cno0LJ#~T)ygrYCfg#|joum5WJ*m`7sZwyhTDBB8e_bntr!G zZR7BehjAr~RqFvkls+RV1*e&f>-5?8-ov|=q_h1;UN|Xc`m0*b?#2zx#xi_3K~Mhj zeZs#`KyUrjPtiOLl^t+^-3-LqwPz_Zjq!zZC;4?RuQETs8rP5PD>V6NJxP8Fh#kem zR?Z6uCdq(V2Khm|clp#7ci(0rV+s4LILoys3!eum8NRMKmplo6T08f6`>DsIYmp2F zS1By}qK6bxx&8%v)9tI!GwVCV!x**tIfIVzgbP^VIESDpLoey2enM7M0YCrE3h{=x zbj!dIu43Yk6+lDV|m-C?n{!P6I`Ng(fwMD6I{>fONx`u7``-}-PzE4ETw?|W@4ySk74wa z*;Ugt0j4br`O?vU83j2HFeW1Q5|~vvO;}ASyia%dynoPPdI!y%7|)_doqYr`&3;OQe$h3wNh#j7@;H3{`s|~JFj9be44YTJN2JTrO9Y$G zDwME;8;MgM^aIa`R=C_|#XW^4w-cfd?*gvkm?wvK*Yn5RM~SJ#fr;x`EIgiF2Chk2(}*+)za0;Gz(=6#X&Ig8 zV^a8swGW_{^&U0pu80a%$Dv0WmU1-aqj^>5=~+h>iZ7$e6TDOOf_T)ne3iaIxe!@z zR48%ZmBG9PjU*Up14P V9DT{TC;T7J)5nHdXieMD{|6(4qLu&v literal 0 HcmV?d00001 diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php new file mode 100644 index 00000000..63776df3 --- /dev/null +++ b/source/includes/write/gridfs.php @@ -0,0 +1,63 @@ +db; +$bucket = $db->selectGridFSBucket(); +// end create bucket + +// start create bucket explicit +$manager = new Manager(''); +$bucket = new Bucket($manager, 'db'); +// end create bucket explicit + +// start create custom bucket +$db = $client->db; +$custom_bucket = $db->selectGridFSBucket(['bucketName' => 'myCustomBucket']); +// end create custom bucket + +// start upload files +$stream = $bucket->openUploadStream("my_file", [ + 'chunkSizeBytes' => 1048576, + 'metadata' => ['contentType' => 'text/plain'] +]); +$stream->write('data to store'); +$stream->close(); +// end upload files + +// start retrieve file info +$files = $bucket->find(); +foreach ($files as $file_doc) { + var_dump($file_doc); +} +// end retrieve file info + +// start download files name +$stream = $bucket->openDownloadStreamByName('my_file'); +$contents = stream_get_contents($stream); +$stream->close(); +// echo $contents if necessary +// end download files name + +// start download files id +$stream = $bucket->openDownloadStream(new ObjectID('66b3c86e672a17b6c8a4a4a9')); +$contents = stream_get_contents($stream); +$stream->close(); +// echo $contents if necessary +// end download files id + +// start rename files +$bucket->rename(new ObjectID('66b3c86e672a17b6c8a4a4a9'), 'new_file_name'); +// end rename files + +// start delete files +$bucket->delete(new ObjectID("66b3c86e672a17b6c8a4a4a9")); +// end delete files +?> \ No newline at end of file diff --git a/source/write.txt b/source/write.txt index 6d95c80a..9ac5e1ff 100644 --- a/source/write.txt +++ b/source/write.txt @@ -12,3 +12,4 @@ Write Data to MongoDB /write/replace /write/insert /write/update + /write/gridfs diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt new file mode 100644 index 00000000..891810e6 --- /dev/null +++ b/source/write/gridfs.txt @@ -0,0 +1,280 @@ +.. _php-gridfs: + +================= +Store Large Files +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: binary large object, blob, storage, code example + +Overview +-------- + +In this guide, you can learn how to store and retrieve large files in +MongoDB by using **GridFS**. GridFS is a specification implemented by +the {+php-library+} that describes how to split files into chunks when storing them +and reassemble them when retrieving them. The library's implementation of +GridFS is an abstraction that manages the operations and organization of +the file storage. + +Use GridFS if the size of your files exceeds the BSON document +size limit of 16MB. For more detailed information on whether GridFS is +suitable for your use case, see :manual:`GridFS ` in the +{+mdb-server+} manual. + +How GridFS Works +---------------- + +GridFS organizes files in a **bucket**, a group of MongoDB collections +that contain the chunks of files and information describing them. The +bucket contains the following collections, named using the convention +defined in the GridFS specification: + +- The ``chunks`` collection stores the binary file chunks. +- The ``files`` collection stores the file metadata. + +When you create a new GridFS bucket, the driver creates the preceding +collections, prefixed with the default bucket name ``fs``, unless +you specify a different name. The driver also creates an index on each +collection to ensure efficient retrieval of the files and related +metadata. The driver creates the GridFS bucket, if it doesn't exist, only when the first write +operation is performed. The driver creates indexes only if they don't exist and when the +bucket is empty. For more information about +GridFS indexes, see :manual:`GridFS Indexes ` +in the {+mdb-server+} manual. + +When storing files with GridFS, the driver splits the files into smaller +chunks, each represented by a separate document in the ``chunks`` collection. +It also creates a document in the ``files`` collection that contains +a file ID, file name, and other file metadata. You can upload the file from +memory or from a stream. See the following diagram to see how GridFS splits +the files when uploaded to a bucket. + +.. figure:: /includes/figures/GridFS-upload.png + :alt: A diagram that shows how GridFS uploads a file to a bucket + +When retrieving files, GridFS fetches the metadata from the ``files`` +collection in the specified bucket and uses the information to reconstruct +the file from documents in the ``chunks`` collection. You can read the file +into memory or output it to a stream. + +.. _gridfs-create-bucket: + +Create a GridFS Bucket +---------------------- + +To store or retrieve files from GridFS, call the ``MongoDB\Database::selectGridFSBucket()`` +method on your database. This method accesses an existing bucket or creates +a new bucket if one does not exist. + +The following example calls the ``selectGridFSBucket()`` on the ``db`` database: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start create bucket + :end-before: end create bucket + +You can also explicitly create a GridFS bucket by calling the +constructor for the ``MongoDB\GridFS\Bucket`` class and passing the following +parameters: + +- ``MongoDB\Driver\Manager`` object, which maintains connections between the + PHP extension and MongoDB +- Name of the database for which to create the bucket, as a string + +The following example explicitly constructs a GridFS bucket: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start create bucket explicit + :end-before: end create bucket explicit + +.. _gridfs-create-custom-bucket: + +Customize the Bucket Name +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To create or reference a bucket with a custom name other than the default name +``fs``, pass an options array to the ``selectGridFSBucket()`` method that sets +the ``bucketName`` option. + +The following example creates a bucket named ``'myCustomBucket'``: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start create custom bucket + :end-before: end create custom bucket + +.. _gridfs-upload-files: + +Upload Files +------------ + +Use the ``MongoDB\GridFS\Bucket::openUploadStream()`` method to +create an upload stream for a given file name. The ``openUploadStream()`` +method allows you to specify configuration information in an options +array, which you can pass as a parameter to the ``openUploadStream()`` method. + +The following example uses an upload stream to upload a file named +``"my_file"`` to a GridFS bucket and writes data to the file. The code +also specifies the ``chunkSizeBytes`` and ``metadata`` options in an +array parameter: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start upload files + :end-before: end upload files + +.. _gridfs-retrieve-file-info: + +Retrieve File Information +------------------------- + +In this section, you can learn how to retrieve file metadata stored in the +``files`` collection of the GridFS bucket. The metadata contains information +about the file it refers to, including: + +- The ``_id`` of the file +- The name of the file +- The length/size of the file +- The upload date and time +- A ``metadata`` document in which you can store any other information + +To retrieve files from a GridFS bucket, call the ``MongoDB\GridFS\Bucket::find()`` +method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\Driver\Cursor`` +instance from which you can access the results. To learn more about ``Cursor`` objects in +the {+php-library+}, see the :ref:`` guide. + +The following code example shows you how to retrieve and print file metadata +from all your files in a GridFS bucket. It uses a ``foreach`` loop to iterate through +the returned cursor and display the results: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start retrieve file info + :end-before: end retrieve file info + +The ``find()`` method accepts various query specifications. You can use +its ``$options`` parameter to specify the sort order, maximum number of documents to return, +and the number of documents to skip before returning. To view a list of available +options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#parameters>`__. + +.. _gridfs-download-files: + +Download Files +-------------- + +You can download files from your MongoDB database by using the +``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` method to +create a download stream. + +The following example shows you how to download a file referenced +by the file name, ``'my_file'``, and read its contents: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start download files name + :end-before: end download files name + +.. note:: + + If there are multiple documents with the same file name, + GridFS will stream the most recent file with the given name (as + determined by the ``uploadDate`` field). + +Alternatively, you can use the ``MongoDB\GridFS\Bucket::openDownloadStream()`` +method, which takes the ``_id`` field of a file as a parameter: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start download files id + :end-before: end download files id + +.. note:: + + The GridFS streaming API cannot load partial chunks. When a download + stream needs to pull a chunk from MongoDB, it pulls the entire chunk + into memory. The 255-kilobyte default chunk size is usually + sufficient, but you can reduce the chunk size to reduce memory + overhead. + +.. _gridfs-rename-files: + +Rename Files +------------ + +Use the ``MongoDB\GridFS\Bucket::rename()`` method to update the name of +a GridFS file in your bucket. You must specify the file to rename by its +``_id`` field rather than its file name. + +The following example shows how to update the ``filename`` field to +``''new_file_name'`` by referencing a document's ``_id`` field: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start rename files + :end-before: end rename files + +.. note:: + + The ``rename()`` method supports updating the name of only one file at + a time. To rename multiple files, retrieve a list of files matching the + file name from the bucket, extract the ``_id`` field from the files you + want to rename, and pass each value in separate calls to the ``rename()`` + method. + +.. _gridfs-delete-files: + +Delete Files +------------ + +Use the ``MongoDB\GridFS\Bucket::delete()`` method to remove a file's collection +document and associated chunks from your bucket. This effectively deletes the file. +You must specify the file by its ``_id`` field rather than its file name. + +The following example shows you how to delete a file by referencing its ``_id`` field: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start delete files + :end-before: end delete files + +.. note:: + + The ``delete()`` method supports deleting only one file at a time. To + delete multiple files, retrieve the files from the bucket, extract + the ``_id`` field from the files you want to delete, and pass each value + in separate calls to the ``delete()`` method. + +API Documentation +----------------- + +To learn more about using the {+php-library+} to store and retrieve large files, +see the following API documentation: + +- `MongoDB\\Database::selectGridFSBucket() <{+api+}/method/MongoDBDatabase-selectGridFSBucket/>`__ +- `MongoDB\GridFS\Bucket::__construct() <{+api+}/method/MongoDBGridFSBucket__construct/>`__ +- `MongoDB\\GridFS\\Bucket::openUploadStream() <{+api+}/method/MongoDBGridFSBucket-openUploadStream/>`__ +- `MongoDB\\GridFS\\Bucket::find() <{+api+}/method/MongoDBGridFSBucket-find/>`__ +- `MongoDB\\GridFS\\Bucket::openDownloadStream() <{+api+}/method/MongoDBGridFSBucket-openDownloadStream/>`__ +- `MongoDB\\GridFS\\Bucket::rename() <{+api+}/method/MongoDBGridFSBucket-rename/>`__ +- `MongoDB\\GridFS\\Bucket::delete() <{+api+}/method/MongoDBGridFSBucket-delete/>`__ \ No newline at end of file From 65e67fbc6cc34f8d06812a1624559d686fa1a4b6 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 10 Sep 2024 15:38:45 -0400 Subject: [PATCH 02/16] fixes --- source/includes/write/gridfs.php | 5 ++--- source/write/gridfs.txt | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 63776df3..f53a5259 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -24,7 +24,7 @@ // end create custom bucket // start upload files -$stream = $bucket->openUploadStream("my_file", [ +$stream = $bucket->openUploadStream('my_file', [ 'chunkSizeBytes' => 1048576, 'metadata' => ['contentType' => 'text/plain'] ]); @@ -58,6 +58,5 @@ // end rename files // start delete files -$bucket->delete(new ObjectID("66b3c86e672a17b6c8a4a4a9")); +$bucket->delete(new ObjectID('66b3c86e672a17b6c8a4a4a9')); // end delete files -?> \ No newline at end of file diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 891810e6..26f46605 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -43,17 +43,17 @@ defined in the GridFS specification: - The ``chunks`` collection stores the binary file chunks. - The ``files`` collection stores the file metadata. -When you create a new GridFS bucket, the driver creates the preceding +When you create a new GridFS bucket, the library creates the preceding collections, prefixed with the default bucket name ``fs``, unless -you specify a different name. The driver also creates an index on each +you specify a different name. The library also creates an index on each collection to ensure efficient retrieval of the files and related -metadata. The driver creates the GridFS bucket, if it doesn't exist, only when the first write -operation is performed. The driver creates indexes only if they don't exist and when the +metadata. The library creates the GridFS bucket, if it doesn't exist, only when the first write +operation is performed. The library creates indexes only if they don't exist and when the bucket is empty. For more information about GridFS indexes, see :manual:`GridFS Indexes ` in the {+mdb-server+} manual. -When storing files with GridFS, the driver splits the files into smaller +When storing files with GridFS, the library splits the files into smaller chunks, each represented by a separate document in the ``chunks`` collection. It also creates a document in the ``files`` collection that contains a file ID, file name, and other file metadata. You can upload the file from @@ -89,7 +89,7 @@ You can also explicitly create a GridFS bucket by calling the constructor for the ``MongoDB\GridFS\Bucket`` class and passing the following parameters: -- ``MongoDB\Driver\Manager`` object, which maintains connections between the +- ``MongoDB\library\Manager`` object, which maintains connections between the PHP extension and MongoDB - Name of the database for which to create the bucket, as a string @@ -129,7 +129,7 @@ method allows you to specify configuration information in an options array, which you can pass as a parameter to the ``openUploadStream()`` method. The following example uses an upload stream to upload a file named -``"my_file"`` to a GridFS bucket and writes data to the file. The code +``'my_file'`` to a GridFS bucket and writes data to the file. The code also specifies the ``chunkSizeBytes`` and ``metadata`` options in an array parameter: @@ -155,7 +155,7 @@ about the file it refers to, including: - A ``metadata`` document in which you can store any other information To retrieve files from a GridFS bucket, call the ``MongoDB\GridFS\Bucket::find()`` -method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\Driver\Cursor`` +method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\library\Cursor`` instance from which you can access the results. To learn more about ``Cursor`` objects in the {+php-library+}, see the :ref:`` guide. @@ -225,7 +225,7 @@ a GridFS file in your bucket. You must specify the file to rename by its ``_id`` field rather than its file name. The following example shows how to update the ``filename`` field to -``''new_file_name'`` by referencing a document's ``_id`` field: +``'new_file_name'`` by referencing a document's ``_id`` field: .. literalinclude:: /includes/write/gridfs.php :language: php @@ -272,7 +272,7 @@ To learn more about using the {+php-library+} to store and retrieve large files, see the following API documentation: - `MongoDB\\Database::selectGridFSBucket() <{+api+}/method/MongoDBDatabase-selectGridFSBucket/>`__ -- `MongoDB\GridFS\Bucket::__construct() <{+api+}/method/MongoDBGridFSBucket__construct/>`__ +- `MongoDB\\GridFS\\Bucket::__construct() <{+api+}/method/MongoDBGridFSBucket__construct/>`__ - `MongoDB\\GridFS\\Bucket::openUploadStream() <{+api+}/method/MongoDBGridFSBucket-openUploadStream/>`__ - `MongoDB\\GridFS\\Bucket::find() <{+api+}/method/MongoDBGridFSBucket-find/>`__ - `MongoDB\\GridFS\\Bucket::openDownloadStream() <{+api+}/method/MongoDBGridFSBucket-openDownloadStream/>`__ From f709846cbe270a2761813fa4d8f184c6f369e0a6 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 10 Sep 2024 16:23:52 -0400 Subject: [PATCH 03/16] code edits --- source/includes/write/gridfs.php | 30 +++++++++++------- source/write/gridfs.txt | 52 ++++++++++++++++++++++---------- 2 files changed, 55 insertions(+), 27 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index f53a5259..766e00c3 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -8,55 +8,63 @@ $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); $client = new MongoDB\Client($uri); +// Creates a GridFS bucket or references an existing one // start create bucket $db = $client->db; $bucket = $db->selectGridFSBucket(); // end create bucket +// Constructs a GridFS bucket // start create bucket explicit $manager = new Manager(''); $bucket = new Bucket($manager, 'db'); // end create bucket explicit +// Creates or references a GridFS bucket with a custom name // start create custom bucket -$db = $client->db; +$db = $client->db_gridfs; $custom_bucket = $db->selectGridFSBucket(['bucketName' => 'myCustomBucket']); // end create custom bucket +// Uploads a file called "my_file" to the GridFS bucket and writes data to it // start upload files $stream = $bucket->openUploadStream('my_file', [ 'chunkSizeBytes' => 1048576, 'metadata' => ['contentType' => 'text/plain'] ]); -$stream->write('data to store'); -$stream->close(); +fwrite($stream, 'Data to store'); +fclose($stream); // end upload files +// Prints information about each file in the bucket // start retrieve file info $files = $bucket->find(); foreach ($files as $file_doc) { - var_dump($file_doc); + echo json_encode($file_doc) , PHP_EOL; } // end retrieve file info +// Downloads the "my_file" file from the GridFS bucket and prints its contents // start download files name $stream = $bucket->openDownloadStreamByName('my_file'); $contents = stream_get_contents($stream); -$stream->close(); -// echo $contents if necessary +echo json_encode($contents) , PHP_EOL; +fclose($stream); // end download files name +// Downloads a file from the GridFS bucket by referencing its ObjectID value // start download files id -$stream = $bucket->openDownloadStream(new ObjectID('66b3c86e672a17b6c8a4a4a9')); +$stream = $bucket->openDownloadStream(new ObjectID('66e0a5487c880f844c0a32b1')); $contents = stream_get_contents($stream); -$stream->close(); -// echo $contents if necessary +fclose($stream); // end download files id +// Renames a file from the GridFS bucket with the specified ObjectID // start rename files -$bucket->rename(new ObjectID('66b3c86e672a17b6c8a4a4a9'), 'new_file_name'); +$bucket->rename(new ObjectID('66e0a5487c880f844c0a32b1'), 'new_file_name'); // end rename files +// Deletes a file from the GridFS bucket with the specified ObjectID // start delete files -$bucket->delete(new ObjectID('66b3c86e672a17b6c8a4a4a9')); +$bucket->delete(new ObjectID('66e0a5487c880f844c0a32b1')); // end delete files diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 26f46605..831d71e9 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -160,17 +160,28 @@ instance from which you can access the results. To learn more about ``Cursor`` o the {+php-library+}, see the :ref:`` guide. The following code example shows you how to retrieve and print file metadata -from all your files in a GridFS bucket. It uses a ``foreach`` loop to iterate through -the returned cursor and display the results: +from files in a GridFS bucket. It uses a ``foreach`` loop to iterate through +the returned cursor and display the contents of the file uploaded in the +:ref:`gridfs-upload-files` example: -.. literalinclude:: /includes/write/gridfs.php - :language: php - :dedent: - :start-after: start retrieve file info - :end-before: end retrieve file info +.. io-code-block:: + :copyable: + + .. input:: /includes/write/gridfs.php + :start-after: start retrieve file info + :end-before: end retrieve file info + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"chunkSize":1048576,"filename":"my_file", + "length":13,"uploadDate":{"$date":{"$numberLong":"..."}},"metadata": + {"contentType":"text\/plain"},"md5":"6b24249b03ea3dd176c5a04f037a658c"} -The ``find()`` method accepts various query specifications. You can use -its ``$options`` parameter to specify the sort order, maximum number of documents to return, +The ``find()`` method accepts various query specifications. You can use its +``$options`` parameter to specify the sort order, maximum number of documents to return, and the number of documents to skip before returning. To view a list of available options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#parameters>`__. @@ -183,14 +194,23 @@ You can download files from your MongoDB database by using the ``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` method to create a download stream. -The following example shows you how to download a file referenced -by the file name, ``'my_file'``, and read its contents: +The following example shows you how to download the file named ``'my_file'``, +which was uploaded in the :ref:`gridfs-upload-files` example, and read its +contents: -.. literalinclude:: /includes/write/gridfs.php - :language: php - :dedent: - :start-after: start download files name - :end-before: end download files name +.. io-code-block:: + :copyable: + + .. input:: /includes/write/gridfs.php + :start-after: start download files name + :end-before: end download files name + :language: php + :dedent: + + .. output:: + :visible: false + + "Data to store" .. note:: From fb135d1d3183febe86390e41447912a4d9efb143 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 10 Sep 2024 16:27:03 -0400 Subject: [PATCH 04/16] fix --- source/write/gridfs.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 831d71e9..9fbf5b3e 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -77,7 +77,8 @@ To store or retrieve files from GridFS, call the ``MongoDB\Database::selectGridF method on your database. This method accesses an existing bucket or creates a new bucket if one does not exist. -The following example calls the ``selectGridFSBucket()`` on the ``db`` database: +The following example calls the ``selectGridFSBucket()`` method on the ``db`` +database: .. literalinclude:: /includes/write/gridfs.php :language: php @@ -91,7 +92,7 @@ parameters: - ``MongoDB\library\Manager`` object, which maintains connections between the PHP extension and MongoDB -- Name of the database for which to create the bucket, as a string +- Name of the database, as a string, for which to create the bucket The following example explicitly constructs a GridFS bucket: From 138990206d74fbead79f23f2def67cf1c8931553 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 11 Sep 2024 13:55:49 -0400 Subject: [PATCH 05/16] RR feedback --- source/includes/write/gridfs.php | 5 +++-- source/write/gridfs.txt | 28 ++++++++++++++++++---------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 766e00c3..2bb2e5df 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -22,8 +22,9 @@ // Creates or references a GridFS bucket with a custom name // start create custom bucket -$db = $client->db_gridfs; -$custom_bucket = $db->selectGridFSBucket(['bucketName' => 'myCustomBucket']); +$custom_bucket = $client->db->selectGridFSBucket( + ['bucketName' => 'myCustomBucket'] +); // end create custom bucket // Uploads a file called "my_file" to the GridFS bucket and writes data to it diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 9fbf5b3e..8b5c3785 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -53,12 +53,12 @@ bucket is empty. For more information about GridFS indexes, see :manual:`GridFS Indexes ` in the {+mdb-server+} manual. -When storing files with GridFS, the library splits the files into smaller +When using GridFS to store files, the library splits the files into smaller chunks, each represented by a separate document in the ``chunks`` collection. It also creates a document in the ``files`` collection that contains a file ID, file name, and other file metadata. You can upload the file from -memory or from a stream. See the following diagram to see how GridFS splits -the files when uploaded to a bucket. +memory or from a stream. View the following diagram to see how GridFS splits +the files when uploaded to a bucket: .. figure:: /includes/figures/GridFS-upload.png :alt: A diagram that shows how GridFS uploads a file to a bucket @@ -129,10 +129,14 @@ create an upload stream for a given file name. The ``openUploadStream()`` method allows you to specify configuration information in an options array, which you can pass as a parameter to the ``openUploadStream()`` method. -The following example uses an upload stream to upload a file named -``'my_file'`` to a GridFS bucket and writes data to the file. The code -also specifies the ``chunkSizeBytes`` and ``metadata`` options in an -array parameter: +This example uses an upload stream to perform the following +actions: + +- Opens a writable stream for a new GridFS file named ``'my_file'`` +- Sets the ``chunkSizeBytes`` and ``metadata`` options in an array parameter + to the ``openUploadStream()`` method +- Calls the ``fwrite()`` method to write data to ``'my_file'``, which the stream points to +- Calls the ``fclose()`` method to close the stream pointing to ``'my_file'`` .. literalinclude:: /includes/write/gridfs.php :language: php @@ -195,9 +199,13 @@ You can download files from your MongoDB database by using the ``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` method to create a download stream. -The following example shows you how to download the file named ``'my_file'``, -which was uploaded in the :ref:`gridfs-upload-files` example, and read its -contents: +This example uses a download stream to perform the following actions: + +- Selects a GridFS file named ``'my_file'``, uploaded in the + :ref:`gridfs-upload-files` example, and opens it as a readable stream +- Calls the ``stream_get_contents()`` method to read the contents of ``'my_file'`` +- Prints the file contents +- Calls the ``fclose()`` method to close the download stream pointing to ``'my_file'`` .. io-code-block:: :copyable: From 5a40fcb076f3b8fa0a254d83abedd2cf38dd6b29 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 11 Sep 2024 13:59:45 -0400 Subject: [PATCH 06/16] phpmethod --- source/write/gridfs.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 8b5c3785..50b12850 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -300,10 +300,10 @@ API Documentation To learn more about using the {+php-library+} to store and retrieve large files, see the following API documentation: -- `MongoDB\\Database::selectGridFSBucket() <{+api+}/method/MongoDBDatabase-selectGridFSBucket/>`__ -- `MongoDB\\GridFS\\Bucket::__construct() <{+api+}/method/MongoDBGridFSBucket__construct/>`__ -- `MongoDB\\GridFS\\Bucket::openUploadStream() <{+api+}/method/MongoDBGridFSBucket-openUploadStream/>`__ -- `MongoDB\\GridFS\\Bucket::find() <{+api+}/method/MongoDBGridFSBucket-find/>`__ -- `MongoDB\\GridFS\\Bucket::openDownloadStream() <{+api+}/method/MongoDBGridFSBucket-openDownloadStream/>`__ -- `MongoDB\\GridFS\\Bucket::rename() <{+api+}/method/MongoDBGridFSBucket-rename/>`__ -- `MongoDB\\GridFS\\Bucket::delete() <{+api+}/method/MongoDBGridFSBucket-delete/>`__ \ No newline at end of file +- :phpmethod:`MongoDB\Database::selectGridFSBucket()` +- :phpmethod:`MongoDB\GridFS\Bucket::__construct()` +- :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::find()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::rename()` +- :phpmethod:`MongoDB\GridFS\Bucket::delete()` \ No newline at end of file From 8ed297575b51af4d8a91ef5017d2b652a4e64702 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 11 Sep 2024 16:18:04 -0400 Subject: [PATCH 07/16] fix --- source/includes/write/gridfs.php | 1 + source/write/gridfs.txt | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 2bb2e5df..0dcceed2 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -4,6 +4,7 @@ use MongoDB\Client; use MongoDB\BSON\ObjectID; use MongoDB\GridFS\Bucket; +use MongoDB\Driver\Manager; $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); $client = new MongoDB\Client($uri); diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 50b12850..fbb259b5 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -90,7 +90,7 @@ You can also explicitly create a GridFS bucket by calling the constructor for the ``MongoDB\GridFS\Bucket`` class and passing the following parameters: -- ``MongoDB\library\Manager`` object, which maintains connections between the +- ``MongoDB\Driver\Manager`` object, which maintains connections between the PHP extension and MongoDB - Name of the database, as a string, for which to create the bucket From c59051410ce8d34847df3bb005f35b83f60d353d Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 11:47:44 -0400 Subject: [PATCH 08/16] JM most feedback --- source/includes/write/gridfs.php | 53 +++++++------ source/write/gridfs.txt | 124 ++++++++++++++++++------------- 2 files changed, 98 insertions(+), 79 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 0dcceed2..d24d5260 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -9,64 +9,63 @@ $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); $client = new MongoDB\Client($uri); -// Creates a GridFS bucket or references an existing one -// start create bucket -$db = $client->db; -$bucket = $db->selectGridFSBucket(); -// end create bucket +// start-to-json +function toJSON(object $document): string +{ + return MongoDB\BSON\Document::fromPHP($document)->toRelaxedExtendedJSON(); +} +// end-to-json -// Constructs a GridFS bucket -// start create bucket explicit -$manager = new Manager(''); -$bucket = new Bucket($manager, 'db'); -// end create bucket explicit +// Creates a GridFS bucket or references an existing one +// start-create-bucket +$bucket = $client->db->selectGridFSBucket(); +// end-create-bucket // Creates or references a GridFS bucket with a custom name -// start create custom bucket +// start-create-custom-bucket $custom_bucket = $client->db->selectGridFSBucket( ['bucketName' => 'myCustomBucket'] ); -// end create custom bucket +// end-create-custom-bucket // Uploads a file called "my_file" to the GridFS bucket and writes data to it -// start upload files +// start-upload-files $stream = $bucket->openUploadStream('my_file', [ - 'chunkSizeBytes' => 1048576, 'metadata' => ['contentType' => 'text/plain'] ]); fwrite($stream, 'Data to store'); fclose($stream); -// end upload files +// end-upload-files // Prints information about each file in the bucket -// start retrieve file info +// start-retrieve-file-info $files = $bucket->find(); foreach ($files as $file_doc) { - echo json_encode($file_doc) , PHP_EOL; + echo toJSON($file_doc), PHP_EOL; } -// end retrieve file info +// end-retrieve-file-info // Downloads the "my_file" file from the GridFS bucket and prints its contents -// start download files name +// start-download-files-name $stream = $bucket->openDownloadStreamByName('my_file'); $contents = stream_get_contents($stream); -echo json_encode($contents) , PHP_EOL; +echo $contents, PHP_EOL; fclose($stream); -// end download files name +// end-download-files-name // Downloads a file from the GridFS bucket by referencing its ObjectID value -// start download files id +// start-download-files-id $stream = $bucket->openDownloadStream(new ObjectID('66e0a5487c880f844c0a32b1')); $contents = stream_get_contents($stream); fclose($stream); -// end download files id +// end-download-files-id // Renames a file from the GridFS bucket with the specified ObjectID -// start rename files +// start-rename-files $bucket->rename(new ObjectID('66e0a5487c880f844c0a32b1'), 'new_file_name'); -// end rename files +// end-rename-files // Deletes a file from the GridFS bucket with the specified ObjectID -// start delete files +// start-delete-files $bucket->delete(new ObjectID('66e0a5487c880f844c0a32b1')); -// end delete files +// end-delete-files diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index fbb259b5..e30105c9 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -56,9 +56,13 @@ in the {+mdb-server+} manual. When using GridFS to store files, the library splits the files into smaller chunks, each represented by a separate document in the ``chunks`` collection. It also creates a document in the ``files`` collection that contains -a file ID, file name, and other file metadata. You can upload the file from -memory or from a stream. View the following diagram to see how GridFS splits -the files when uploaded to a bucket: +a file ID, file name, and other file metadata. You can upload the file by passing +a stream to the {+php-library+} to consume or creating a new stream and writing to it +directly. To learn more about streams, see `Streams <{+php-manual+}/book.stream.php>`__ +in the PHP manual. + +View the following diagram to see how GridFS splits the files when uploaded to +a bucket: .. figure:: /includes/figures/GridFS-upload.png :alt: A diagram that shows how GridFS uploads a file to a bucket @@ -66,7 +70,8 @@ the files when uploaded to a bucket: When retrieving files, GridFS fetches the metadata from the ``files`` collection in the specified bucket and uses the information to reconstruct the file from documents in the ``chunks`` collection. You can read the file -into memory or output it to a stream. +by writing its contents to an existing stream or creating a new stream that points +to the file. .. _gridfs-create-bucket: @@ -83,41 +88,57 @@ database: .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start create bucket - :end-before: end create bucket + :start-after: start-create-bucket + :end-before: end-create-bucket -You can also explicitly create a GridFS bucket by calling the -constructor for the ``MongoDB\GridFS\Bucket`` class and passing the following -parameters: +.. _gridfs-create-custom-bucket: -- ``MongoDB\Driver\Manager`` object, which maintains connections between the - PHP extension and MongoDB -- Name of the database, as a string, for which to create the bucket +Customize the Bucket +~~~~~~~~~~~~~~~~~~~~ -The following example explicitly constructs a GridFS bucket: +You can customize the GridFS bucket configuration by passing an array that specifies +option values to the ``selectGridFSBucket()`` method. The following table describes +some options you can set in the array: -.. literalinclude:: /includes/write/gridfs.php - :language: php - :dedent: - :start-after: start create bucket explicit - :end-before: end create bucket explicit +.. list-table:: + :widths: 30 70 + :header-rows: 1 -.. _gridfs-create-custom-bucket: + * - Option + - Description -Customize the Bucket Name -~~~~~~~~~~~~~~~~~~~~~~~~~ + * - ``bucketName`` + - | Specifies the bucket name to use as a prefix for the files and chunks collections. + The default value is ``'fs'``. + | **Type**: ``string`` -To create or reference a bucket with a custom name other than the default name -``fs``, pass an options array to the ``selectGridFSBucket()`` method that sets -the ``bucketName`` option. + * - ``chunkSizeBytes`` + - | Specifies the chunk size that GridFS splits files into. The default value is ``261120``. + | **Type**: ``integer`` -The following example creates a bucket named ``'myCustomBucket'``: + * - ``readConcern`` + - | Specifies the read concern to use for bucket operations. The default value is the + database's read concern. + | **Type**: ``MongoDB\Driver\ReadConcern`` + + * - ``readPreference`` + - | Specifies the read preference to use for bucket operations. The default value is the + database's read preference. + | **Type**: ``MongoDB\Driver\ReadPreference`` + + * - ``writeConcern`` + - | Specifies the write concern to use for bucket operations. The default value is the + database's write concern. + | **Type**: ``MongoDB\Driver\WriteConcern`` + +The following example creates a bucket named ``'myCustomBucket'`` by passing an +array to ``selectGridFSBucket()`` that sets the ``bucketName`` option: .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start create custom bucket - :end-before: end create custom bucket + :start-after: start-create-custom-bucket + :end-before: end-create-custom-bucket .. _gridfs-upload-files: @@ -133,7 +154,7 @@ This example uses an upload stream to perform the following actions: - Opens a writable stream for a new GridFS file named ``'my_file'`` -- Sets the ``chunkSizeBytes`` and ``metadata`` options in an array parameter +- Sets the ``metadata`` option in an array parameter to the ``openUploadStream()`` method - Calls the ``fwrite()`` method to write data to ``'my_file'``, which the stream points to - Calls the ``fclose()`` method to close the stream pointing to ``'my_file'`` @@ -141,8 +162,8 @@ actions: .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start upload files - :end-before: end upload files + :start-after: start-upload-files + :end-before: end-upload-files .. _gridfs-retrieve-file-info: @@ -173,8 +194,8 @@ the returned cursor and display the contents of the file uploaded in the :copyable: .. input:: /includes/write/gridfs.php - :start-after: start retrieve file info - :end-before: end retrieve file info + :start-after: start-retrieve-file-info + :end-before: end-retrieve-file-info :language: php :dedent: @@ -211,8 +232,8 @@ This example uses a download stream to perform the following actions: :copyable: .. input:: /includes/write/gridfs.php - :start-after: start download files name - :end-before: end download files name + :start-after: start-download-files-name + :end-before: end-download-files-name :language: php :dedent: @@ -233,8 +254,8 @@ method, which takes the ``_id`` field of a file as a parameter: .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start download files id - :end-before: end download files id + :start-after: start-download-files-id + :end-before: end-download-files-id .. note:: @@ -251,7 +272,7 @@ Rename Files Use the ``MongoDB\GridFS\Bucket::rename()`` method to update the name of a GridFS file in your bucket. You must specify the file to rename by its -``_id`` field rather than its file name. +``_id`` field rather than its file name. The following example shows how to update the ``filename`` field to ``'new_file_name'`` by referencing a document's ``_id`` field: @@ -259,16 +280,15 @@ The following example shows how to update the ``filename`` field to .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start rename files - :end-before: end rename files + :start-after: start-rename-files + :end-before: end-rename-files -.. note:: +.. note:: File Revisions The ``rename()`` method supports updating the name of only one file at - a time. To rename multiple files, retrieve a list of files matching the - file name from the bucket, extract the ``_id`` field from the files you - want to rename, and pass each value in separate calls to the ``rename()`` - method. + a time. If you want to rename each file revision, or files with different upload + times that share the same file name, collect the ``_id`` values of each revision. + Then, pass each value in separate calls to the ``rename()`` method. .. _gridfs-delete-files: @@ -284,15 +304,15 @@ The following example shows you how to delete a file by referencing its ``_id`` .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start delete files - :end-before: end delete files + :start-after: start-delete-files + :end-before: end-delete-files -.. note:: +.. note:: File Revisions - The ``delete()`` method supports deleting only one file at a time. To - delete multiple files, retrieve the files from the bucket, extract - the ``_id`` field from the files you want to delete, and pass each value - in separate calls to the ``delete()`` method. + The ``delete()`` method supports deleting only one file at a time. If + you want to delete each file revision, or files with different upload + times that share the same file name, collect the ``_id`` values of each revision. + Then, pass each value in separate calls to the ``delete()`` method. API Documentation ----------------- @@ -301,9 +321,9 @@ To learn more about using the {+php-library+} to store and retrieve large files, see the following API documentation: - :phpmethod:`MongoDB\Database::selectGridFSBucket()` -- :phpmethod:`MongoDB\GridFS\Bucket::__construct()` - :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` - :phpmethod:`MongoDB\GridFS\Bucket::find()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` - :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` - :phpmethod:`MongoDB\GridFS\Bucket::rename()` - :phpmethod:`MongoDB\GridFS\Bucket::delete()` \ No newline at end of file From 5a8cd805151b6ecf65ddf5b3bd94c8b459d4069a Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 12:40:37 -0400 Subject: [PATCH 09/16] alternate upload/download methods --- source/includes/write/gridfs.php | 26 +++++++++-- source/write/gridfs.txt | 76 ++++++++++++++++++++++++++++---- 2 files changed, 90 insertions(+), 12 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index d24d5260..ddddd66b 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -29,13 +29,22 @@ function toJSON(object $document): string // end-create-custom-bucket // Uploads a file called "my_file" to the GridFS bucket and writes data to it -// start-upload-files +// start-open-upload-stream $stream = $bucket->openUploadStream('my_file', [ 'metadata' => ['contentType' => 'text/plain'] ]); fwrite($stream, 'Data to store'); fclose($stream); -// end-upload-files +// end-open-upload-stream + +// Uploads data to a stream, then writes the stream to a GridFS file +// start-upload-from-stream +$stream = fopen('php://temp', 'w+b'); +fwrite($stream, 'Data to store'); +rewind($stream); + +$bucket->uploadFromStream('new_file', $stream); +// end-upload-from-stream // Prints information about each file in the bucket // start-retrieve-file-info @@ -46,12 +55,12 @@ function toJSON(object $document): string // end-retrieve-file-info // Downloads the "my_file" file from the GridFS bucket and prints its contents -// start-download-files-name +// start-open-download-stream-name $stream = $bucket->openDownloadStreamByName('my_file'); $contents = stream_get_contents($stream); echo $contents, PHP_EOL; fclose($stream); -// end-download-files-name +// end-open-download-stream-name // Downloads a file from the GridFS bucket by referencing its ObjectID value // start-download-files-id @@ -60,6 +69,15 @@ function toJSON(object $document): string fclose($stream); // end-download-files-id +// Downloads an entire GridFS file to a download stream +// start-download-to-stream +$stream = fopen('php://temp', 'w+b'); +$bucket->downloadToStream( + new ObjectID('66e0a5487c880f844c0a32b1'), + $stream +); +// end-download-to-stream + // Renames a file from the GridFS bucket with the specified ObjectID // start-rename-files $bucket->rename(new ObjectID('66e0a5487c880f844c0a32b1'), 'new_file_name'); diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index e30105c9..1bbc3829 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -145,10 +145,19 @@ array to ``selectGridFSBucket()`` that sets the ``bucketName`` option: Upload Files ------------ -Use the ``MongoDB\GridFS\Bucket::openUploadStream()`` method to -create an upload stream for a given file name. The ``openUploadStream()`` -method allows you to specify configuration information in an options -array, which you can pass as a parameter to the ``openUploadStream()`` method. +You can upload files to a GridFS bucket by using the following methods: + +- ``MongoDB\GridFS\Bucket::openUploadStream()``: Opens a new upload stream + to which you can write file contents +- ``MongoDB\GridFS\Bucket::uploadFromStream()``: Uploads the contents of + an existing stream to a GridFS file + +Write to an Upload Stream +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``openUploadStream()`` method to create an upload stream for a given +file name. The ``openUploadStream()`` method allows you to specify configuration +information in an options array, which you can pass as a parameter. This example uses an upload stream to perform the following actions: @@ -162,8 +171,29 @@ actions: .. literalinclude:: /includes/write/gridfs.php :language: php :dedent: - :start-after: start-upload-files - :end-before: end-upload-files + :start-after: start-open-upload-stream + :end-before: end-open-upload-stream + +Upload an Existing Stream +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``uploadFromStream()`` method to upload the contents of a stream to +a new GridFS file. The ``uploadFromStream()`` method allows you to specify configuration +information in an options array, which you can pass as a parameter. + +This example performs the following actions: + +- Calls the ``fopen()`` method to create a temporary memory-based stream + that you can write to and read from +- Calls the ``fwrite()`` method to write data to the stream +- Calls the ``uploadFromStream()`` method to upload the contents of the stream + to a GridFS file named ``'new_file'`` + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-upload-from-stream + :end-before: end-upload-from-stream .. _gridfs-retrieve-file-info: @@ -216,6 +246,17 @@ options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#pa Download Files -------------- +You can download files from a GridFS bucket by using the following methods: + +- ``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` or + ``MongoDB\GridFS\Bucket::openDownloadStream()``: Opens a new download stream + from which you can read the file contents +- ``MongoDB\GridFS\Bucket::downloadToStream()``: Writes the entire file to + an existing download stream + +Read From a Download Stream +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + You can download files from your MongoDB database by using the ``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` method to create a download stream. @@ -232,8 +273,8 @@ This example uses a download stream to perform the following actions: :copyable: .. input:: /includes/write/gridfs.php - :start-after: start-download-files-name - :end-before: end-download-files-name + :start-after: start-open-download-stream-name + :end-before: end-open-download-stream-name :language: php :dedent: @@ -265,6 +306,25 @@ method, which takes the ``_id`` field of a file as a parameter: sufficient, but you can reduce the chunk size to reduce memory overhead. +Download to an Existing Stream +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can download the contents of a GridFS file to an existing stream +by calling the ``MongoDB\GridFS\Bucket::downloadToStream()`` method +on your bucket. + +This example performs the following actions: + +- Calls the ``fopen()`` method to open a download stream +- Downloads a file that has an ``_id`` value of ``ObjectID('66e0a5487c880f844c0a32b1')`` + to the stream + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-download-to-stream + :end-before: end-download-to-stream + .. _gridfs-rename-files: Rename Files From 7ccbe17231edbabd4aae6c07547569bbfef2df95 Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 13:53:52 -0400 Subject: [PATCH 10/16] file revisions --- source/includes/write/gridfs.php | 7 +++++++ source/write/gridfs.txt | 29 ++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index ddddd66b..3948302f 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -69,6 +69,13 @@ function toJSON(object $document): string fclose($stream); // end-download-files-id +// Downloads the original "my_file" file from the GridFS bucket +// start-download-file-revision +$stream = $bucket->openDownloadStreamByName('my_file', ['revision' => 0]); +$contents = stream_get_contents($stream); +fclose($stream); +// end-open-download-stream-name + // Downloads an entire GridFS file to a download stream // start-download-to-stream $stream = fopen('php://temp', 'w+b'); diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 1bbc3829..19daecf1 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -211,10 +211,13 @@ about the file it refers to, including: - A ``metadata`` document in which you can store any other information To retrieve files from a GridFS bucket, call the ``MongoDB\GridFS\Bucket::find()`` -method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\library\Cursor`` +method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\Driver\Cursor`` instance from which you can access the results. To learn more about ``Cursor`` objects in the {+php-library+}, see the :ref:`` guide. +Example +~~~~~~~ + The following code example shows you how to retrieve and print file metadata from files in a GridFS bucket. It uses a ``foreach`` loop to iterate through the returned cursor and display the contents of the file uploaded in the @@ -306,6 +309,30 @@ method, which takes the ``_id`` field of a file as a parameter: sufficient, but you can reduce the chunk size to reduce memory overhead. +Download a File Revision +~~~~~~~~~~~~~~~~~~~~~~~~ + +When your bucket contains multiple files that share the same file name, +GridFS chooses the most recently uploaded version of the file by default. +To differentiate between each file that shares the same name, GridFS assigns them +a revision number, ordered by upload time. + +The original file revision number is ``0`` and the next most recent file revision +number is ``1``. You can also specify negative values that correspond to the recency +of the revision. The revision value ``-1`` references the most recent revision and ``-2`` +references the next most recent revision. + +You can instruct GridFS to download a specific file revision by passing an options +array to the ``openDownloadStreamByName()`` method and specifying the ``revision`` +option. The following example reads the contents of the original file named +``'my_file'`` rather than the most recent revision: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-download-file-revision + :end-before: end-download-file-revision + Download to an Existing Stream ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 279a5a511d9170a6b0f5fd6ba6c553374b5b8df9 Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 13:54:25 -0400 Subject: [PATCH 11/16] code fix --- source/includes/write/gridfs.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 3948302f..4c64838f 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -74,7 +74,7 @@ function toJSON(object $document): string $stream = $bucket->openDownloadStreamByName('my_file', ['revision' => 0]); $contents = stream_get_contents($stream); fclose($stream); -// end-open-download-stream-name +// end-download-file-revision // Downloads an entire GridFS file to a download stream // start-download-to-stream From 3e7d5e08a6d6639fb26ae29d91adf3fceea98cdc Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 13:59:02 -0400 Subject: [PATCH 12/16] tojson --- source/write/gridfs.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 19daecf1..a1aac877 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -244,6 +244,17 @@ The ``find()`` method accepts various query specifications. You can use its and the number of documents to skip before returning. To view a list of available options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#parameters>`__. +.. note:: + + The preceding example calls the ``toJSON()`` to print file metadata as + Extended JSON, defined in the following code: + + .. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-to-json + :end-before: end-to-json + .. _gridfs-download-files: Download Files From 6d401a0bfab4fa0dfd93c9af80ad9129a283fb6a Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 14:28:08 -0400 Subject: [PATCH 13/16] edits --- source/write/gridfs.txt | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index a1aac877..669549be 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -221,7 +221,7 @@ Example The following code example shows you how to retrieve and print file metadata from files in a GridFS bucket. It uses a ``foreach`` loop to iterate through the returned cursor and display the contents of the file uploaded in the -:ref:`gridfs-upload-files` example: +:ref:`gridfs-upload-files` examples: .. io-code-block:: :copyable: @@ -235,9 +235,11 @@ the returned cursor and display the contents of the file uploaded in the .. output:: :visible: false - {"_id":{"$oid":"..."},"chunkSize":1048576,"filename":"my_file", - "length":13,"uploadDate":{"$date":{"$numberLong":"..."}},"metadata": - {"contentType":"text\/plain"},"md5":"6b24249b03ea3dd176c5a04f037a658c"} + { "_id" : { "$oid" : "..." }, "chunkSize" : 261120, "filename" : "my_file", + "length" : 13, "uploadDate" : { ... }, "metadata" : { "contentType" : "text/plain" }, + "md5" : "6b24249b03ea3dd176c5a04f037a658c" } + { "_id" : { "$oid" : "..." }, "chunkSize" : 261120, "filename" : "new_file", + "length" : 13, "uploadDate" : { ... }, "md5" : "6b24249b03ea3dd176c5a04f037a658c" } The ``find()`` method accepts various query specifications. You can use its ``$options`` parameter to specify the sort order, maximum number of documents to return, @@ -246,7 +248,7 @@ options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#pa .. note:: - The preceding example calls the ``toJSON()`` to print file metadata as + The preceding example calls the ``toJSON()`` method to print file metadata as Extended JSON, defined in the following code: .. literalinclude:: /includes/write/gridfs.php @@ -420,8 +422,10 @@ see the following API documentation: - :phpmethod:`MongoDB\Database::selectGridFSBucket()` - :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::uploadFromStream()` - :phpmethod:`MongoDB\GridFS\Bucket::find()` - :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` - :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` - :phpmethod:`MongoDB\GridFS\Bucket::rename()` - :phpmethod:`MongoDB\GridFS\Bucket::delete()` \ No newline at end of file From 34a6abf4c57f8a542d2ad9909a999bb0de15bd3c Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 15:12:08 -0400 Subject: [PATCH 14/16] JM feedback 2 --- source/includes/write/gridfs.php | 11 ++++------- source/write/gridfs.txt | 14 ++++++++------ 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 4c64838f..d231407a 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -39,11 +39,8 @@ function toJSON(object $document): string // Uploads data to a stream, then writes the stream to a GridFS file // start-upload-from-stream -$stream = fopen('php://temp', 'w+b'); -fwrite($stream, 'Data to store'); -rewind($stream); - -$bucket->uploadFromStream('new_file', $stream); +$file = fopen('/path/to/file', 'rb'); +$bucket->uploadFromStream('new_file', $file); // end-upload-from-stream // Prints information about each file in the bucket @@ -78,10 +75,10 @@ function toJSON(object $document): string // Downloads an entire GridFS file to a download stream // start-download-to-stream -$stream = fopen('php://temp', 'w+b'); +$stream = fopen('/path/to/output-file', 'wb'); $bucket->downloadToStream( new ObjectID('66e0a5487c880f844c0a32b1'), - $stream + $stream, ); // end-download-to-stream diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 669549be..e7c339da 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -183,9 +183,8 @@ information in an options array, which you can pass as a parameter. This example performs the following actions: -- Calls the ``fopen()`` method to create a temporary memory-based stream - that you can write to and read from -- Calls the ``fwrite()`` method to write data to the stream +- Calls the ``fopen()`` method to open a file located at ``/path/to/file`` + as a stream in binary read (``rb``) mode - Calls the ``uploadFromStream()`` method to upload the contents of the stream to a GridFS file named ``'new_file'`` @@ -320,7 +319,9 @@ method, which takes the ``_id`` field of a file as a parameter: stream needs to pull a chunk from MongoDB, it pulls the entire chunk into memory. The 255-kilobyte default chunk size is usually sufficient, but you can reduce the chunk size to reduce memory - overhead. + overhead or increase the chunk size when working with larger files. + For more information about setting the chunk size, see the + :ref:`gridfs-create-custom-bucket` section of this page. Download a File Revision ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -355,8 +356,9 @@ on your bucket. This example performs the following actions: -- Calls the ``fopen()`` method to open a download stream -- Downloads a file that has an ``_id`` value of ``ObjectID('66e0a5487c880f844c0a32b1')`` +- Calls the ``fopen()`` method to open a file located at ``/path/to/output-file`` + as a stream in binary write (``wb``) mode +- Downloads a GridFS file that has an ``_id`` value of ``ObjectID('66e0a5487c880f844c0a32b1')`` to the stream .. literalinclude:: /includes/write/gridfs.php From af8020c9f6761f60fb24bc66646cfc99cba8e67a Mon Sep 17 00:00:00 2001 From: norareidy Date: Fri, 13 Sep 2024 15:19:24 -0400 Subject: [PATCH 15/16] edits --- source/includes/write/gridfs.php | 4 ++-- source/write/gridfs.txt | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index d231407a..21087f60 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -39,7 +39,7 @@ function toJSON(object $document): string // Uploads data to a stream, then writes the stream to a GridFS file // start-upload-from-stream -$file = fopen('/path/to/file', 'rb'); +$file = fopen('/path/to/input_file', 'rb'); $bucket->uploadFromStream('new_file', $file); // end-upload-from-stream @@ -75,7 +75,7 @@ function toJSON(object $document): string // Downloads an entire GridFS file to a download stream // start-download-to-stream -$stream = fopen('/path/to/output-file', 'wb'); +$stream = fopen('/path/to/output_file', 'wb'); $bucket->downloadToStream( new ObjectID('66e0a5487c880f844c0a32b1'), $stream, diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index e7c339da..f5cbf3e8 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -152,6 +152,8 @@ You can upload files to a GridFS bucket by using the following methods: - ``MongoDB\GridFS\Bucket::uploadFromStream()``: Uploads the contents of an existing stream to a GridFS file +.. _gridfs-open-upload-stream: + Write to an Upload Stream ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -183,7 +185,7 @@ information in an options array, which you can pass as a parameter. This example performs the following actions: -- Calls the ``fopen()`` method to open a file located at ``/path/to/file`` +- Calls the ``fopen()`` method to open a file located at ``/path/to/input_file`` as a stream in binary read (``rb``) mode - Calls the ``uploadFromStream()`` method to upload the contents of the stream to a GridFS file named ``'new_file'`` @@ -219,7 +221,7 @@ Example The following code example shows you how to retrieve and print file metadata from files in a GridFS bucket. It uses a ``foreach`` loop to iterate through -the returned cursor and display the contents of the file uploaded in the +the returned cursor and display the contents of the files uploaded in the :ref:`gridfs-upload-files` examples: .. io-code-block:: @@ -279,7 +281,7 @@ create a download stream. This example uses a download stream to perform the following actions: - Selects a GridFS file named ``'my_file'``, uploaded in the - :ref:`gridfs-upload-files` example, and opens it as a readable stream + :ref:`gridfs-open-upload-stream` example, and opens it as a readable stream - Calls the ``stream_get_contents()`` method to read the contents of ``'my_file'`` - Prints the file contents - Calls the ``fclose()`` method to close the download stream pointing to ``'my_file'`` @@ -356,7 +358,7 @@ on your bucket. This example performs the following actions: -- Calls the ``fopen()`` method to open a file located at ``/path/to/output-file`` +- Calls the ``fopen()`` method to open a file located at ``/path/to/output_file`` as a stream in binary write (``wb``) mode - Downloads a GridFS file that has an ``_id`` value of ``ObjectID('66e0a5487c880f844c0a32b1')`` to the stream From e1f1190c74d219aa0327f12778e27d8a894bcc55 Mon Sep 17 00:00:00 2001 From: norareidy Date: Mon, 16 Sep 2024 14:52:36 -0400 Subject: [PATCH 16/16] JM last feedback --- source/includes/write/gridfs.php | 26 ++++++++++++-------------- source/write/gridfs.txt | 2 +- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php index 21087f60..bb94ce63 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -1,13 +1,11 @@ openDownloadStream(new ObjectID('66e0a5487c880f844c0a32b1')); +$stream = $bucket->openDownloadStream(new ObjectId('66e0a5487c880f844c0a32b1')); $contents = stream_get_contents($stream); fclose($stream); // end-download-files-id @@ -75,19 +73,19 @@ function toJSON(object $document): string // Downloads an entire GridFS file to a download stream // start-download-to-stream -$stream = fopen('/path/to/output_file', 'wb'); +$file = fopen('/path/to/output_file', 'wb'); $bucket->downloadToStream( - new ObjectID('66e0a5487c880f844c0a32b1'), - $stream, + new ObjectId('66e0a5487c880f844c0a32b1'), + $file, ); // end-download-to-stream -// Renames a file from the GridFS bucket with the specified ObjectID +// Renames a file from the GridFS bucket with the specified ObjectId // start-rename-files -$bucket->rename(new ObjectID('66e0a5487c880f844c0a32b1'), 'new_file_name'); +$bucket->rename(new ObjectId('66e0a5487c880f844c0a32b1'), 'new_file_name'); // end-rename-files -// Deletes a file from the GridFS bucket with the specified ObjectID +// Deletes a file from the GridFS bucket with the specified ObjectId // start-delete-files -$bucket->delete(new ObjectID('66e0a5487c880f844c0a32b1')); +$bucket->delete(new ObjectId('66e0a5487c880f844c0a32b1')); // end-delete-files diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index f5cbf3e8..20bbc6dd 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -360,7 +360,7 @@ This example performs the following actions: - Calls the ``fopen()`` method to open a file located at ``/path/to/output_file`` as a stream in binary write (``wb``) mode -- Downloads a GridFS file that has an ``_id`` value of ``ObjectID('66e0a5487c880f844c0a32b1')`` +- Downloads a GridFS file that has an ``_id`` value of ``ObjectId('66e0a5487c880f844c0a32b1')`` to the stream .. literalinclude:: /includes/write/gridfs.php