Php Mongodb

In order to connect php to the mongodb server. We require the library of mongodb.

Below is the code to connnect to mongodb using php.

1) Make the connection with the server

<?php

$con= new MongoClient(“addressofserver:port”);

?>

Here MongoClient class creates the connnection with the server. You can also connnect to mongodb database on your local machine also. For that you have to provide (127.0.0.1) in the address.

2) Once the connection to the mongodb is done. The next item is to connect to the database.

$database=$con->newdatabase;

The above example creates a new database , if it does not exist on the server. If the database is there on the server,it simply connects to that database.

In traditional database(RDBMS) we have to create database if it does not exist. But in case of mongodb php, the database is created automatically , if it does not exists.

3) Once we have our database created, the next thing is to create a collection. The collection is created in the db.

Below is the syntax of creating a collection
$collect=$database->newcollection;
This will create a new collection in the databse.

4) Once the collection is created in the mongodb database. The next things is to insert document (json values) in the
collection.
$values={“name” :”john”, “subject” : “mongodb”}
once we have declared our json variable , the next step is to save this in the collection.
$collect->insert($values);
This is very simple way to insert values in collection using the document .

In this php mongodb tutorial , you learnt simple way to connect to mongodb server and store values.