{"id":274,"date":"2012-08-12T18:21:56","date_gmt":"2012-08-12T10:21:56","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=274"},"modified":"2018-09-03T22:35:13","modified_gmt":"2018-09-03T14:35:13","slug":"inserting-a-document-into-a-collection-in-mongodb-with-php","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/inserting-a-document-into-a-collection-in-mongodb-with-php\/","title":{"rendered":"Inserting a document into a collection in MongoDB with PHP"},"content":{"rendered":"<p>Assume that we have a <a href=\"http:\/\/www.mongodb.org\/\" title=\"MongoDB home page\" target=\"_blank\">MongoDB<\/a> server <a href=\"http:\/\/www.techcoil.com\/blog\/installing-mongodb-as-a-windows-service\/\" title=\"Installing MongoDB as a windows service\" target=\"_blank\">installed as a windows service<\/a> on the same machine as our web server. The server listens on port <strong>33333<\/strong>. <\/p>\n<p>We met a new friend, and we want to save some details about her. That night, before bidding farewell, she said: \"Remember me, I am <strong>Mary Jane<\/strong>. You can write to me at <strong>mary.jane@gmail.com<\/strong>\".<\/p>\n<p>Although that's all we have about her, this is sufficient for us to insert a document about Mary into our MongoDB database. <\/p>\n<p>Inserting documents into collections in MongoDB with PHP consists of the following steps:<\/p>\n<ul>\n<li>Derive an instance of the <code>MongoCollection<\/code> class that represents the MongoDB collection to insert documents.<\/li>\n<li>Define the document to insert.<\/li>\n<li>Define additional options for the insert.<\/li>\n<li>Execute the insert function of the <code>MongoCollection<\/code> instance.<\/li>\n<\/ul>\n<h3>Derive an instance of the MongoCollection class that represents the MongoDB collection to insert documents<\/h3>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\r\n$connection = new Mongo('mongodb:\/\/localhost:33333');\r\n$friendCollection = $connection-&gt;selectCollection(&quot;contactDb&quot;, &quot;friend&quot;);\r\n\r\n?&gt;\r\n<\/pre>\n<p>To instruct our MongoDB server to help us remember Mary, we first get an instance of the <a href=\"http:\/\/php.net\/manual\/en\/class.mongo.php\" title=\"PHP Mongo class reference\" target=\"_blank\"><code>Mongo<\/code><\/a> class that connects to our server. We then utilize the <a href=\"http:\/\/www.php.net\/manual\/en\/mongo.selectcollection.php\" title=\"PHP Mongo selectCollection function reference\" target=\"_blank\"><code>selectionCollection<\/code><\/a> function of the <code>Mongo<\/code> instance to get an instance of the <a href=\"http:\/\/php.net\/manual\/en\/class.mongocollection.php\" title=\"PHP MongoCollection class reference\" target=\"_blank\"><code>MongoCollection<\/code><\/a> class that points to the <code>\"friend\"<\/code> collection in the <code>\"contactDb\"<\/code> database.<\/p>\n<h3>Define the document to insert<\/h3>\n<p>In PHP, documents are mapped to associative arrays. With that, we can declare an array which contains the two pieces of data which Mary had provided:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\r\n$mary = array(\r\n    'name'  =&gt; 'Mary Jane',\r\n    'email' =&gt; 'mary.jane@gmail.com'\r\n);\r\n\r\n?&gt;\r\n<\/pre>\n<p>We associate the string \"<strong>Mary Jane<\/strong>\" with the \"<code>name<\/code>\" key and the string \"<strong>mary.jane@gmail.com<\/strong>\" with the \"<code>email<\/code>\" key.<\/p>\n<h3>Define additional options for the insert<\/h3>\n<p>We can specify a set of additional options to control how the PHP driver will perform the insertion of Mary's details into the \"friend\" collection. Such options are specified in an associate array with certain key\/value pairs.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\r\n$insertOptions = array(\r\n\t'safe'    =&gt; true,\r\n\t'fsync'   =&gt; true,\r\n\t'timeout' =&gt; 10000\r\n);\r\n\r\n?&gt;\r\n<\/pre>\n<p>To ensure that details provided by Mary are correctly saved into the \"friend\" collection, we specify a <code>true<\/code> as the value for the \"<code>safe<\/code>\" and \"<code>fsync<\/code>\" keys. <\/p>\n<p>With \"<code>safe<\/code>\" having a value of <code>true<\/code>, our PHP program will wait for the database response and throw a <a href=\"http:\/\/www.php.net\/manual\/en\/class.mongocursorexception.php\" title=\"PHP MongoCursorException class reference\" target=\"_blank\"><code>MongoCursorException<\/code><\/a> if the insert is unsuccessful. This overrides the default behavior of the insert operation in which the PHP driver is ignorant to whether Mary's details are successfully remembered in the \"friend\" collection.<\/p>\n<p>With \"<code>fsync<\/code>\" having a value of <code>true<\/code>, our PHP program will force the driver to synchronize the insert to disk before indicating the insert to be successful. <\/p>\n<p>With \"<code>timeout<\/code>\" having a value of 10000, our PHP driver will wait for at most 10 seconds for the insert operation to complete. If not, a <code>MongoCursorTimeoutException<\/code> will be thrown.<\/p>\n<h3>Execute the insert function of the MongoCollection instance<\/h3>\n<p>Once we have gathered the data to insert and the options to apply in the form of arrays, we are ready to perform the insertion of the document. <\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\r\ntry {\r\n\t\r\n\t$results = $friendCollection-&gt;insert($mary, $insertOptions);\r\n\t\r\n\tprint '&lt;h2&gt;Result from saving Mary\\'s details&lt;\/h2&gt;';\r\n\tprint '&lt;pre&gt;';\r\n\tprint_r($results);\r\n\tprint '&lt;\/pre&gt;';\r\n\t\r\n\tprint '&lt;h2&gt;Mary\\'s details in database&lt;\/h2&gt;';\r\n\tprint '&lt;pre&gt;';\r\n\tprint_r($mary);\r\n\tprint '&lt;\/pre&gt;';\t\r\n}\r\ncatch (MongoCursorException $mce) {\r\n\t\/\/ Triggered when the insert fails\r\n}\r\ncatch (MongoCursorTimeoutException $mcte) {\r\n\t\/\/ Triggered when insert does not complete within value given by timeout\r\n} \/\/ end try -catch \r\n\r\n?&gt;\r\n<\/pre>\n<p>We insert the document that describes Mary into our \"<code>friend<\/code>\" collection via the <a href=\"http:\/\/php.net\/manual\/en\/mongocollection.insert.php\" title=\"PHP MongoCollection insert function reference\" target=\"_blank\"><code>insert<\/code><\/a> function of the <code>MongoCollection<\/code> class. <\/p>\n<p>We place the <code>$friendCollection->insert<\/code> function call in a <code>try<\/code> clause because of the options that we have specified for the insert operation.<\/p>\n<p>In the event when the document cannot be inserted successfully, a <code>MongoCursorException<\/code> will be thrown. One such case would be to execute the <code>$friendCollection->insert<\/code> a second time:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n\r\n\/\/ ...\r\n$results = $friendCollection-&gt;insert($mary, $insertOptions);\r\n$results = $friendCollection-&gt;insert($mary, $insertOptions);\r\n\/\/ ...\r\n\r\n<\/pre>\n<p>If the PHP driver waited more than 10 seconds for a response from the database, a <a href=\"http:\/\/php.net\/manual\/en\/class.mongocursortimeoutexception.php\" title=\"PHP MongoCursorTimeoutException class reference\" target=\"_blank\"><code>MongoCursorTimeoutException<\/code><\/a> will be thrown.<\/p>\n<h4>The results from the document insertion<\/h4>\n<p>If we are able to execute <code>$friendCollection->insert<\/code> without encountering any exceptions, an array containing details of the document insertion will be available via the <code>$results<\/code> variable. On my machine, I was able to get the following output by executing <code>print_r<\/code> on the <code>$results<\/code> array:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nArray\r\n(\r\n    &#x5B;n] =&gt; 0\r\n    &#x5B;connectionId] =&gt; 1\r\n    &#x5B;waited] =&gt; 11\r\n    &#x5B;err] =&gt; \r\n    &#x5B;ok] =&gt; 1\r\n)\r\n<\/pre>\n<ul>\n<li><strong><code>n<\/code><\/strong> points to the number of objects that are affected by the insertion. Since insertion of documents does not affect any objects in the database, <code>n<\/code> points to a 0.<\/li>\n<li><strong><code>connectionId<\/code><\/strong> points to the identification number of the MongoDB connection that was used to perform the document insertion.<\/li>\n<li><strong><code>waited<\/code><\/strong> points to the time in milliseconds that the PHP driver had waited for the document insertion to be successful.<\/li>\n<li><strong><code>err<\/code><\/strong> points to an error message that describe an error that had occurred during document insertion. Since it had pointed to a null value, we can determine that the document insertion was successful.<\/li>\n<li><strong><code>ok<\/code><\/strong> points to a value that indicates whether the document insertion was successful. A value of 1 means that Mary's details were being inserted to the \"friend\" collection successfully.<\/li>\n<\/ul>\n<h4>Getting the unique id of the document that was just inserted into the MongoDB collection<\/h4>\n<p>A MongoDB server will help to generate a unique id for every document that it manages when possible. If the <code>_id<\/code> key is absent from the document array, our MongoDB server will help us create one during document insertion. Indeed, passing the <code>$mary<\/code> variable into the <code>print_r<\/code> function after we call <code>$friendCollection->insert<\/code> reveals the value of the \"<code>_id<\/code>\" key that our MongoDB server had created for us:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nArray\r\n(\r\n    &#x5B;name] =&gt; Mary Jane\r\n    &#x5B;email] =&gt; mary.jane@gmail.com\r\n    &#x5B;_id] =&gt; MongoId Object\r\n        (\r\n            &#x5B;$id] =&gt; 502770ad5d79f9800b000009\r\n        )\r\n)\r\n<\/pre>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/connecting-to-and-disconnecting-from-a-mongodb-server-in-php\/\" title=\"Connecting to and disconnecting from a MongoDB server in PHP\" target=\"_blank\">Connecting to and disconnecting from a MongoDB server in PHP<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/mongodb-at-a-conceptual-level\/\" title=\"MongoDB at a conceptual level\" target=\"_blank\">MongoDB at a conceptual level<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/installing-mongodb-as-a-windows-service\/\" title=\"Installing MongoDB as a windows service\" target=\"_blank\">Installing MongoDB as a windows service<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/my-first-look-at-mongodb-why-i-will-want-to-use-mongodb-in-my-next-project\/\" title=\"My first look at MongoDB \u2013 Why I will want to use MongoDB in my next project\" target=\"_blank\">My first look at MongoDB \u2013 Why I will want to use MongoDB in my next project<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/getting-documents-from-mongodb-collections-with-php\/\" title=\"Getting documents from MongoDB collections with PHP\" target=\"_blank\"><\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-4q\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-4q&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-4q&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F274&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>Assume that we have a <a href=\"http:\/\/www.mongodb.org\/\" title=\"MongoDB home page\" target=\"_blank\">MongoDB<\/a> server <a href=\"http:\/\/www.techcoil.com\/blog\/installing-mongodb-as-a-windows-service\/\" title=\"Installing MongoDB as a windows service\" target=\"_blank\">installed as a windows service<\/a> on the same machine as our web server. The server listens on port <strong>33333<\/strong>. <\/p>\n<p>We met a new friend, and we want to save some details about her. That night, before bidding farewell, she said: &#8220;Remember me, I am <strong>Mary Jane<\/strong>. You can write to me at <strong>mary.jane@gmail.com<\/strong>&#8220;.<\/p>\n<p>Although that&#8217;s all we have about her, this is sufficient for us to insert a document about Mary into our MongoDB database. <\/p>\n<p>Inserting documents into collections in MongoDB with PHP consists of the following steps:<\/p>\n<ul>\n<li>Derive an instance of the <code>MongoCollection<\/code> class that represents the MongoDB collection to insert documents.<\/li>\n<li>Define the document to insert.<\/li>\n<li>Define additional options for the insert.<\/li>\n<li>Execute the insert function of the <code>MongoCollection<\/code> instance.<\/li>\n<\/ul>\n","protected":false},"author":1,"featured_media":1218,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[154,152,13],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/mongoDB-logo.jpg","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-4q","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/274"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=274"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/274\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1218"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=274"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=274"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}