{"id":270,"date":"2012-08-04T21:52:56","date_gmt":"2012-08-04T13:52:56","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=270"},"modified":"2018-09-03T22:34:58","modified_gmt":"2018-09-03T14:34:58","slug":"connecting-to-and-disconnecting-from-a-mongodb-server-in-php","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/connecting-to-and-disconnecting-from-a-mongodb-server-in-php\/","title":{"rendered":"Connecting to and disconnecting from a MongoDB server in PHP"},"content":{"rendered":"<p>The first step to manipulate data in the MongoDB ecosystem is to connect to a <a href=\"http:\/\/www.mongodb.org\/\" title=\"MongoDB homepage\" target=\"_blank\">MongoDB<\/a> server. In php, we can use the <a href=\"http:\/\/www.php.net\/manual\/en\/class.mongo.php\" title=\"Link to PHP Mongo class\"><code>Mongo<\/code><\/a> class to help us connect to one or more MongoDB servers. <\/p>\n<p>For the purpose of this demonstration, let's assume that we had installed a <a href=\"http:\/\/www.techcoil.com\/blog\/installing-mongodb-as-a-windows-service\/\" title=\"Installing MongoDB as a windows service\" target=\"_blank\">MongoDB server instance as a windows service<\/a> which listens on port <strong>12345<\/strong>. In addition, our PHP web server runs on the same machine as the MongoDB server. <\/p>\n<h3>Connecting to a MongoDB server<\/h3>\n<p>We can connect to the MongoDB server by specifying the server address and port in the <a href=\"http:\/\/www.mongodb.org\/display\/DOCS\/Connections\" title=\"Link to MongoDB connections reference\" target=\"_blank\">standard connection string format<\/a> and passing the string into the <code>Mongo<\/code> constructor.  <\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$connection = new Mongo('mongodb:\/\/localhost:12345');\r\n?&gt;\r\n<\/pre>\n<h3>Using some functions of the Mongo instance<\/h3>\n<h4>Getting information about the databases managed by the MongoDB server<\/h4>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$dbArray = $connection-&gt;listDBs();\r\necho '&lt;pre&gt;';\r\nprint_r($dbArray);\r\necho '&lt;\/pre&gt;'\r\n?&gt;\r\n<\/pre>\n<p>The <code>listDBs<\/code> function of the Mongo instance can be used to retrieve some information about the databases that are managed by the <code>MongoDB<\/code> server that we had connected to. The return value is an array that resembles the following format:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nArray\r\n(\r\n    &#x5B;databases] =&gt; Array\r\n        (\r\n            &#x5B;0] =&gt; Array\r\n                (\r\n                    &#x5B;name] =&gt; admin\r\n                    &#x5B;sizeOnDisk] =&gt; 83886080\r\n                    &#x5B;empty] =&gt; \r\n                )\r\n\r\n            &#x5B;1] =&gt; Array\r\n                (\r\n                    &#x5B;name] =&gt; techcoil\r\n                    &#x5B;sizeOnDisk] =&gt; 83886080\r\n                    &#x5B;empty] =&gt; \r\n                )\r\n\r\n            &#x5B;2] =&gt; Array\r\n                (\r\n                    &#x5B;name] =&gt; local\r\n                    &#x5B;sizeOnDisk] =&gt; 1\r\n                    &#x5B;empty] =&gt; 1\r\n                )\r\n\r\n        )\r\n\r\n    &#x5B;totalSize] =&gt; 167772160\r\n    &#x5B;ok] =&gt; 1\r\n)\r\n<\/pre>\n<h4>Gaining code access to a database instance<\/h4>\n<p>There are two ways which we can gain access to a database managed by the MongoDB server:<\/p>\n<ol>\n<li>\n<strong>Via the selectDB function<\/strong><\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$techcoilDB = $connection-&gt;selectDB('techcoil');\r\n?&gt;\r\n<\/pre>\n<\/li>\n<li>\n<strong>Via the __get magic function<\/strong><\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$techcoilDB = $connection-&gt;techcoil;\r\n?&gt;\r\n<\/pre>\n<\/li>\n<\/ol>\n<p>Both of the code segments retrieve an instance of <a href=\"http:\/\/www.php.net\/manual\/en\/class.mongodb.php\" title=\"PHP MongoDB class reference\"><code>MongoDB<\/code><\/a> that allow us to manipulate the \"techcoil\" database. <\/p>\n<h4>Gaining code access to a collection within a database instance<\/h4>\n<p>Apart from gaining code access to a database, the <code>Mongo<\/code> class also contains the <code>selectCollection<\/code> function which allows us to gain code access to a collection within the database.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$userCollection = $collection-&gt;selectCollection(&quot;techcoil&quot;, &quot;User&quot;);\r\n?&gt;\r\n<\/pre>\n<p>The code segment retrieves a <a href=\"http:\/\/www.php.net\/manual\/en\/class.mongocollection.php\" title=\"PHP MongoCollection reference\" target=\"_blank\"><code>MongoCollection<\/code><\/a> instance and set it to the <code>$userCollection<\/code> variable. We can then manipulate the \"User\" collection that is in the \"techcoil\" database via the <code>$userCollection<\/code> variable.<\/p>\n<h3>Disconnecting from a MongoDB server<\/h3>\n<p>To disconnect from the MongoDB server, we use the same variable which holds the Mongo instance that we had used for connection and execute its close function.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$connection-&gt;close();\r\n?&gt;\r\n<\/pre>\n<h3>Related posts<\/h3>\n<ul>\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\/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\/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\/getting-documents-from-mongodb-collections-with-php\/\" title=\"Getting documents from MongoDB collections with PHP\" target=\"_blank\"><\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/inserting-a-document-into-a-collection-in-mongodb-with-php\/\" title=\"Inserting a document into a collection in MongoDB with PHP\" target=\"_blank\">Inserting a document into a collection in MongoDB with PHP<\/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-4m\" 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-4m&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-4m&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%2F270&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>The first step to manipulate data in the MongoDB ecosystem is to connect to a <a href=\"http:\/\/www.mongodb.org\/\" title=\"MongoDB homepage\" target=\"_blank\">MongoDB<\/a> server. In php, we can use the <a href=\"http:\/\/www.php.net\/manual\/en\/class.mongo.php\" title=\"Link to PHP Mongo class\"><code>Mongo<\/code><\/a> class to help us connect to one or more MongoDB servers. <\/p>\n<p>For the purpose of this demonstration, let&#8217;s assume that we had installed a <a href=\"http:\/\/www.techcoil.com\/blog\/installing-mongodb-as-a-windows-service\/\" title=\"Installing MongoDB as a windows service\" target=\"_blank\">MongoDB server instance as a windows service<\/a> which listens on port <strong>12345<\/strong>. In addition, our PHP web server runs on the same machine as the MongoDB instance. <\/p>\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,153,13],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/mongoDB-logo.jpg","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-4m","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/270"}],"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=270"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/270\/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=270"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=270"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=270"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}