Web Programming TutorialsUsing MongoDB with PHP

Using MongoDB with PHP

Today we will be learning to use a document based database called MongoDB to work with PHP in this Using MongoDB with PHP tutorial.

  • What is MongoDB?
    • MongoDB is a document database which falls into a documents-oriented NoSQL databases group.
    • It is a open source database application and provides high performance, availability and easy scalability.
    • MongoDB is exactly like the RDBMS databases.
    • A mongoDB has number of databases in it. A database holds number of collections and collection in turn holds number of documents.
    • A database in mongoDB is similar to RDBMS database, the collection in mongoDB is equivalent to a table in RDBMS database and the document in mongoDB is a record stored in the collection.
    • MongoDB database has a database named test by default in it.
    • Document is a basic unit of database in mogoDB which is stored in collection. Documents are the JSON objects which are stored in the collection in a BSON format. BSON is the binary representation of JSON objects. You can also say document as a multidimensional associative array with key-value pairs.
  • Installation of MongoDB on Windows OS:
    • To install MongoDB on Windows OS, first open the site www.mongodb.org in the browser.
    • Click on the downloads link on the site, then click on the stable release suitable for your OS.
    • Once the download is finished, extract the zip file and move it to C:/.
    • The mongoDB requires a data folder in C:\ ( C:\data\db) to store its files. If it is not present you have to create it.
    • To start MongoDB, open the command prompt and write the following statements there:
    • C:\>cd mongodb\bin
      C:\mongodb\bin> mongod
      
    • Now after that start and stop the service MongoDB via command line:
    • net start MongoDB
      net stop MongoDB
      
    • The MongoDB server is already built to work with web server but not with PHP. So to make it interact with PHP, there is another method.
    • We will have to install the mongo-php-driver to make it interact with PHP.
    • Download the zip file of the driver from the following link:
    • https://github.com/mongodb/mongo-php-driver/downloads
    • Extract the zip file and copy the php_mongo.dll file from the extracted stuff. Paste this copied file into the extension folder in the xampp folder (C:\xampp\php\ext).
    • Then open the php.ini file inside PHP installation and write the following line in it:
    • extension=php_mongo.dll
    • Save the file and close it and then restart the xampp.
    • Now open a notepad++ file, save it as index.php in the htdocs folder of xampp folder and write the following statement inside it:
    • <?php
      	phpinfo();
      ?>
    • After opening the file in browser; if you see mongo as the output, your installation is successful.

    Now let us try various operations through PHP with mongoDB database.

  • Connecting to MongoDB database:
    • Connecting to a mongoDB database is very easy. It is shown below:
    • $con=new Mongo();
    • This will connect you to the mongoDB database at the localhost server.
  • Selecting/creating a database:
    • To select a database we have to specify its name. If the database is not present, it will be created.
    • The database can be selected by specifying it in selectDB method or directly specifying its name. See both the ways below:
    • $db=connection_variable->selectDB(‘database_name’);
    • OR
    • $db=connection_variable->database_name;
    • In the above statements the $db is any variable used to point to the database, connection_variable means the variable used for connection for eg. $con used in the statement to connect to mongoDB database. Database_name is the name of the database we want to create or select.
    • Let us create a database named Shop in the mongoDB database. For this create a new folder named mongodb in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in the newly created mongodb folder.
    • Write the following code in index.php file:
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "Connected Successfully!!";
      	//creating a new database
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!";
      ?>
      
    • Here we first connected to mongoDB database and then created a database named Shop in it.
  • Creating a Collection:
    • Next step after the database creation is to create a collection to store data in the form of documents.
    • Collection is created as follows:
    • $coll=database->collection_name;
    • OR
    • $coll=database->selectCollection(‘Collection_name’);
    • OR
    • $coll=database->createCollection(‘Collection_name’);
    • Here, $coll is any variable used to point the collection and database is the database in which we want to create the collection, for eg. $db which points to the database Shop in the concept of creating/selecting database. Collection_name is the name of the collection to be created.
    • We know that collection in mongoDb is equivalent to a table in RDBMS databases. So we will create a collection named Products in our Shop database.
    • The code is shown below:
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "<br>Connected Successfully!!<br>";
      	//creating a new database named Shop
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!<br>";
      	//creating a collection named Products
      	$prod=$db->products;
      	echo "Connection <b>products</b> created successfully!!<br>";
      ?>
      
    • Here we have created the collection products using the statement
    • $prod=$db->products;
  • Inserting a record in collection:
    • To insert a record in a collection a document is used.
    • A document has a group of key-value pair structure as shown below:
    • {
      	field1: value1,
      	field2: value2,
      	field3: value3,
      	…
      	fieldN: valueN
      }
    • We just have to declare an associative array containing the field of collection as its key and the value in the field as its value. Then put this array in the insert() method to insert it in the collection.
    • The code for it is shown below:
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "<br>Connected Successfully!!<br>";
      	//creating a new database named Shop
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!<br>";
      	//creating a collection named Products
      	$prod=$db->products;
      	echo "Connection <b>products</b> created successfully!!<br>";
      	//creating an array of record to insert into collection
      	$p=array(‘prod_name’ => ‘Laptop’, ‘prod_price’ => 40000, ‘prod_qty’ => 500, ‘prod_colour’ =>’black’, ‘save_date’ => new MongoDate());
      	//inserting the document into collection
      	$prod->insert($p);
      	echo “Record inserted successfully!!”;
      ?>
      
    • Here we have inserted a record for a black colour laptop in the Products collection using the statement
      $prod->insert($p);
    • When we insert the record in the collection, a object id is automatically generated by BSON and is added to the array $p with the field name _id. This will be the id of that particular inserted record.
    • We have used insert() method in this example, but we can even use the save() method which have the capability of updating an existing record and inserting the new record in the collection.
  • Searching for documents and reading them:
    • The task of searching all documents from the collection is done using find() method.
    • Let us see how it is done:
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "<br>Connected Successfully!!<br>";
      	//creating a new database named Shop
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!<br>";
      	//creating a collection named Products
      	$prod=$db->products;
      	echo "Connection <b>products</b> created successfully!!<br>";
      	//creating an array of record to insert into collection
      	$p=array(‘prod_name’ => ‘Laptop’, ‘prod_price’ => 40000, ‘prod_qty’ => 500, ‘prod_colour’ =>’black’, ‘save_date’ => new MongoDate());
      	//inserting the document into collection
      	$prod->insert($p);
      	echo “Record inserted successfully!!”;
      	//searching the records
      	$records=$prod->find();
      	//reading the documents
      	foreach($records as $r)
      	{
      		echo “Product: ”.$r[‘prod_name’].”<br>”;
      		echo “Cost: ”.$r[‘prod_price’].”<br>”;
      		echo “Quantity: ”.$r[‘prod_qty’].”<br>”;
      		echo “Colour: ”.$r[‘prod_colour’].”<br>”;
      }
      ?>
      
    • We have used the statement
      $records=$prod->find();

      to find the documents from the collection. All the records are read using the find() method.

    • The records are displayed using the foreach loop.
    • If you want to search for a single record, you can use findOne() method which returns only the record which satisfies the given required criterion.
    • If you have id of a particular product with you, you can search for it using findOne() method as follows:
    • $id=’3455d576775 65776’;
      $record=$prod->findOne(array(‘_id’) => new MongoID($id));
    • Here the details of the product with the given id will be searched and returned for you. You can then display it.
  • Updating a document:
    • If you want to modify any document in the collection you can change it using the update() method.
    • By default update() method updates a single document, but it can update multiple documents which satisfy the criterion also if its multiple option is set to true.
    • Let us update the colour of product Laptop from black to red.
    • The code is given below:
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "<br>Connected Successfully!!<br>";
      	//creating a new database named Shop
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!<br>";
      	//creating a collection named Products
      	$prod=$db->products;
      	echo "Connection <b>products</b> created successfully!!<br>";
      	//updating the record using its id
      $id=’3455d576775 65776’;
      	$prod->update(array(‘_id’ => ‘$id’), array(‘$set’=>array(‘prod_colour’ => ‘red’)));
      	$record=$prod->findOne(array(‘_id’ => ‘$id’));
      	echo “colour of ”.$record[‘prod_name’].” is ”.$record[$prod_colour]; 
      ?>
      
    • Here we updated the record of product Laptop with black colour using its id with the following statement:
    • $prod->update(array(‘_id’ => ‘$id’), array(‘$set’=>array(‘prod_colour’ => ‘red’)));
    • Then it is again displayed to see if it is modified successfully.
  • Delete a document:
    • To delete some document we can use remove() method.
    • remove() method allows you to delete a document from a collection according to the specified criterion.
    • Let us see how it is used by deleting the prod_colour field from the document stored in our Products collection.
    • <?php
      	//connecting mongodb database
      	$con=new Mongo();
      	echo "<br>Connected Successfully!!<br>";
      	//creating a new database named Shop
      	$db=$con->Shop;
      	echo "Database <b>Products</b> created successfully!!<br>";
      	//creating a collection named Products
      	$prod=$db->products;
      	echo "Connection <b>products</b> created successfully!!<br>";
      	//deleting a document from a collection
      	$prod->remove(array(‘prod_colour’ => ‘red’), false);
      ?>
      
    • Here we have used remove() method to delete the prod_colour field value from the document using the following statement:
    • $prod->remove(array(‘prod_colour’ => ‘red’), false);
    • The remove() method contains the array containing the field and its value to be removed and the second parameter is a Boolean type with value false, which is used for the justOne field of remove() method.

Thus we studied about the mongoDB database, how to use it with PHP and also some of the basic operations with it in this Using MongoDB with PHP tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -