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


$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 ( in the address.

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


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
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
$values={“name” :”john”, “subject” : “mongodb”}
once we have declared our json variable , the next step is to save this in the collection.
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.