{"id":633,"date":"2021-11-14T20:49:17","date_gmt":"2021-11-15T01:49:17","guid":{"rendered":"https:\/\/molecularsciences.org\/content\/?p=633"},"modified":"2024-02-08T08:44:12","modified_gmt":"2024-02-08T13:44:12","slug":"quick-introduction-to-mongodb","status":"publish","type":"post","link":"https:\/\/molecularsciences.org\/content\/quick-introduction-to-mongodb\/","title":{"rendered":"Quick introduction to MongoDB"},"content":{"rendered":"\n<p>MongoDB is document based NoSQL database. This means that:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>it has no schema<\/li><li>it has no relations<\/li><li>it is agile and scaleable<\/li><li>stores information in nested documents of two-dimensional key\/value pairs.<\/li><\/ul>\n\n\n\n<p>What are the benefits of using MongoDB?<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>you do not have to pre-define your schema or data model<\/li><li>works nicely with JavaScript<\/li><li>ideal for client-side applications<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Installing MongoDB<\/h3>\n\n\n\n<p><strong>Installing MongoDB on Mac with Homebrew<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ brew update\n$ brew install mongodb\n<\/code><\/pre>\n\n\n\n<p>Add mongodb binaries to your path<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ vi ~\/.bash_profile\n$ export PATH=\"\/user\/local\/Cellar\/mongodb\"\n<\/code><\/pre>\n\n\n\n<p>Create data directory<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ sudo mkdir -p \/data\/db\n<\/code><\/pre>\n\n\n\n<p>Make sure that the user account using mongod has access to this directory. If you are getting errors when you run mongod, try the following to test.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ sudo chmod -R 777 \/data\/db\n$ mongod\n<\/code><\/pre>\n\n\n\n<p>You should see \u201cwaiting for connections on port 27017\u201d. Accept the Mac prompt about this port. Leave it running or you won&#8217;t be able to run Mongo commands.<\/p>\n\n\n\n<p>On ANOTHER TERMINAL, do the following to test<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ mongo\n&gt; show dbs\n&gt; db\n&gt; use db_name\n&gt; db.users.save({ name: 'Hello' });\n&gt; db.users.find();\n{ \"_id\" : ObjectId(\"5718f9e188eb6ebd7fd588b7\"), \"name\" : \"Hello\" }\n&gt; db.users.find({name:'Hello'});\n&gt; db.users.update({name:'Hello'},{name:'Hello World'});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n&gt; db.users.remove({})\n&gt; db.users.remove({name:'Hello'})\n&gt; exit\n<\/code><\/pre>\n\n\n\n<p>This is called the Mongo Shell. It is an interactive JavaScript interpreter. You can many commands on it like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; for(i=0;i&lt;5;i++) print(\"number \"+i);\n<\/code><\/pre>\n\n\n\n<p>Following are number, string, and object declarations<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; a = 1\n&gt; b = \"str\"\n&gt; c = {\"d\":1}\n&gt; c.d\n&gt; c&#91;\"d\"]\n<\/code><\/pre>\n\n\n\n<p>Objects are denoted in BSON format. See&nbsp;<a target=\"_blank\" href=\"http:\/\/www.bsonspec.org\/\" rel=\"noreferrer noopener\">bsonspec.org<\/a>. Last two lines show how to access object variables.<\/p>\n\n\n\n<p>For help, type the following in Mongo Shell<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; help\n&gt; help keys\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Mongo CRUD<\/h3>\n\n\n\n<p>CRUD stands for Create Retrieve Update Delete. These refer to the creating, retrieving, updating, and deleting rows. Following tables shows statements used by SQL and Mongo for CRUD<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>&#8211;<\/th><th>SQL<\/th><th>Mongo<\/th><\/tr><\/thead><tbody><tr><td>C<\/td><td>Insert<\/td><td>Insert<\/td><\/tr><tr><td>R<\/td><td>Select<\/td><td>Find<\/td><\/tr><tr><td>U<\/td><td>Update<\/td><td>Update<\/td><\/tr><tr><td>D<\/td><td>Delete<\/td><td>Remove<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>In MongoDB, CRUD operations exist as methods or functions in a programming language API. A query language is not used.<\/p>\n\n\n\n<p>Following are the CRUD command you need to know:<\/p>\n\n\n\n<p><strong>Create Database<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>use Continents\n<\/code><\/pre>\n\n\n\n<p><strong>List databases<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show databases\n<\/code><\/pre>\n\n\n\n<p><strong>Create Collection (Mongo term for table)<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createCollection(\"Countries\")\ndb.createCollection(\"Dummy\")\n<\/code><\/pre>\n\n\n\n<p><strong>List collections<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show collections\n<\/code><\/pre>\n\n\n\n<p><strong>drop collection<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.Dummy.drop()\n<\/code><\/pre>\n\n\n\n<p><strong>Insert data in a collection<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>a = {\"name\":\"Canada\", \"capital\":\"Toronto\"}\ndb.Countries.save(a)\n<\/code><\/pre>\n\n\n\n<p><strong>Query data from collection<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.Countries.find({\"name\":\"Canada\"});\n<\/code><\/pre>\n\n\n\n<p><strong>Update a Document (row) in a collection<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.Countries.update(\n    {\"name\":\"Canada\"},\n    {$set: {\"capital\":\"Ottawa\"}}\n)\n<\/code><\/pre>\n\n\n\n<p><strong>Remove a document<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.Countries.remove({_id:100...})\n<\/code><\/pre>\n\n\n\n<p><strong>Copy database<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.CopyDatabase(\"Countries\", \"Pays\")\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Making PHP and MongoDB to work together<\/h3>\n\n\n\n<p>Making PHP and MongoDB to work together is a two part process.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Install MongoDB driver for PHP<\/li><li>Install PHP library for MongoDB<\/li><\/ol>\n\n\n\n<p>Type the following in your terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ brew install homebrew\/php\/php55-mongodb\n<\/code><\/pre>\n\n\n\n<p>My PHP version is 5.5. If you are running a different version, you would need to install a different extension.<\/p>\n\n\n\n<p>To test whether the driver was installed correctly, save the following PHP code as test.php<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nprint_r(phpversion(\"mongodb\"));\n?&gt;\n<\/code><\/pre>\n\n\n\n<p>Run the code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ php test.php\n<\/code><\/pre>\n\n\n\n<p>Your output should be something like the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1.1.8\n<\/code><\/pre>\n\n\n\n<p>The easiest way to install PHP library for MongoDB is to use composer. Composer is a package handler for PHP like PECL and PEAR. First of all, check whether you have composer installed on your system.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ which composer\n<\/code><\/pre>\n\n\n\n<p>The following commands will install composer on a Mac<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ curl -sS https:\/\/getcomposer.org\/installer | php\n$ mv composer.phar \/usr\/local\/bin\/composer\n$ composer init\n<\/code><\/pre>\n\n\n\n<p>Then install PHP MongoDB library<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ composer require \"mongodb\/mongodb\"\n<\/code><\/pre>\n\n\n\n<p>Save the following PHP code as test1.php<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\n\/\/ use Composer packages\nrequire 'vendor\/autoload.php'; \n\n\/\/ connect to MongoDB\n$client = new MongoDB\\Client(\"mongodb:\/\/localhost:27017\");\n\n\/\/ use\/create \"testdb\" database and \"testtable\" table\n$collection = $client-&gt;testdb-&gt;testtable;\n\n\/\/ insert data in the database\n$result = $collection-&gt;insertOne( &#91; 'name' =&gt; 'hello', 'description' =&gt; 'world' ] );\n\n\/\/ get the inserted object id\necho \"Object ID = '{$result-&gt;getInsertedId()}'\";\n?&gt;\n<\/code><\/pre>\n\n\n\n<p>Run the code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ php test1.php\n<\/code><\/pre>\n\n\n\n<p>You should get an output like the following<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Object ID = '57c464e99d74ed076a3c2301'\n<\/code><\/pre>\n\n\n\n<p>To check whether the data was inserted correctly, type mongod on one terminal and mongo on another terminal. In the mongo terminal type the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; show dbs\nlocal   0.000GB\ntestdb  0.000GB\n&gt; use testdb\nswitched to db testdb\n&gt; db.getCollectionNames()\n&#91; \"testtable\" ]\n&gt; db.testtable.find()\n{ \"_id\" : ObjectId(\"57c464e99d74ed076a3c2301\"), \"name\" : \"hello\", \"description\" : \"world\" }\n<\/code><\/pre>\n\n\n\n<p>The first command lists all databases. Second command is selects the database you want to work with. The third command lists all collections (tables). The last command lists the contents of the collection.<\/p>\n\n\n\n<p>To fetch contents of a selection using PHP code,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nrequire 'vendor\/autoload.php'; \n$client = new MongoDB\\Client(\"mongodb:\/\/localhost:27017\");\n$collection = $client-&gt;testdb-&gt;testtable;\n\n\/\/ find data\n$rs = $collection-&gt;find( &#91; 'name' =&gt; 'hello', 'description' =&gt; 'world' ] );\n\n\/\/ fetch the collection\nforeach ($rs as $rw) {\n    print $rw&#91;'_id'] . \"\\t\" . $rw&#91;'name'] . \"\\t\" . $rw&#91;'description'] . \"\\n\";\n}\n?&gt;\n<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>57c464e99d74ed076a3c2301    hello   world\n<\/code><\/pre>\n\n\n\n<p>Note the use on find() instead of insertOne().<\/p>\n","protected":false},"excerpt":{"rendered":"<p>MongoDB is document based NoSQL database. This means that: it has no schema it has no relations it is agile and scaleable stores information in nested documents of two-dimensional key\/value pairs. What are the benefits of using MongoDB? you do not have to pre-define your schema or data model works nicely with JavaScript ideal for [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16],"tags":[],"class_list":["post-633","post","type-post","status-publish","format-standard","hentry","category-database"],"_links":{"self":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/633","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/comments?post=633"}],"version-history":[{"count":1,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/633\/revisions"}],"predecessor-version":[{"id":634,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/posts\/633\/revisions\/634"}],"wp:attachment":[{"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/media?parent=633"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/categories?post=633"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/molecularsciences.org\/content\/wp-json\/wp\/v2\/tags?post=633"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}