This tutorial provides an introduction to basic database operations using the mongo shell. MongoDB is a document database that provides high performance, high availability, and easy scalability.
MongoDB is a free and open-source cross-platform document-oriented database program with NoSQL database. It stores data in json format. MongoDb is developed by MongoDB Inc in 2007.
To access MongoDB from PHP you need:
1) The MongoDB server running. The server is the “mongod” file,
not the “mongo” client (note the “d” at the end).
2) The MongoDB PHP driver installed.
To make connection string & select the database in php simply used the below snippets.
Create a config.php
file.
1 2 3 4 5 6 7 8 |
<?php #connect to mongodb $m = new MongoClient(); echo "Connection with database is successful."; #select a database $db = $m->mydb; echo "Database mydb selected"; ?> |
1 2 3 4 5 6 7 8 9 10 11 |
<?php #include the connect file required("config.php"); #Select all data $all = $collection->find(); foreach ($all as $document) { echo $document["name"] . "\n"; } ?> |
In the part of useful CRUD there is ability to delete the data records. MonogoDB provides a method remove() for this which only takes an array of data attributes as the criteria to removing the data records.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php #include the connect file required("config.php"); #Now remove the document $collection->remove(array("title"=>"MongoDB Tutorial"),false); echo "Documents deleted successfully"; #Now display the available data $cursor = $collection->find(); #Iterate cursor to display name of data echo "Updated document"; foreach ($cursor as $document) { echo $document["name"] . "\n"; } ?> |
In the CRUD operations there is also ability to update the records. In MongoDB have a simple method save() for this which require an array of criteria to know which records would be updated. Bellow is the example fo updating the data records.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php #Update the data $collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB Tutorial"))); echo "Document updated successfully"; #Now display the updated data $cursor = $collection->find(); #Iiterate cursor to display name of data echo "Updated document"; foreach ($cursor as $document) { echo $document["name"] . "\n"; } ?> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Database, learn mongodb, mongo database tutorial, mongo database tutorials, mongo db tutorials, MongoDB, mongodb tutorial, PHP, Web development