A PHP program to insert individual and batch data into MongoDB database

December 26, 2012
By

In this article, we will create a PHP application that inserts documents in to a collection individually and as a batch in a MongoDB database.

This article is an extension to the article titled “Connecting and authenticating to MongoDB database from PHP using MongoClient“.

Using this program, we are inserting data into “students” collection of “university” database of MongoDB.


Documents available in “students” collection before executing php program

> use university
switched to db university

> db.auth("admu","new_pass")
1
> show collections
students
system.indexes
system.users
> db.students.find()
{ "_id" : ObjectId("50d69d6a1d26a8a0c1eaecf8"), "name" : "Rajesh", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 81 }
{ "_id" : ObjectId("50d69de81d26a8a0c1eaecf9"), "name" : "John", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 79 }
{ "_id" : ObjectId("50d69e5bbe5a399f4650f9a3"), "name" : "Firoz", "age" : 22, "gender" : "M", "course" : "BTECH", "marks" : 88 }
{ "_id" : ObjectId("50d69e5bbe5a399f4650f9a4"), "name" : "Alan", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 68 }
{ "_id" : ObjectId("50d69eb8be5a399f4650f9a5"), "name" : "Anjali", "age" : 20, "gender" : "F", "course" : "MBA", "marks" : 67 }
{ "_id" : ObjectId("50d69eb8be5a399f4650f9a6"), "name" : "Ali Khan", "age" : 20, "gender" : "M", "course" : "MBA", "marks" : 59 }

Create a file namely “students_insert.php” in the document root of the web server and add the given below code

This program insert students data into “students” collection individually and as a bulk.

<?php
    /**
    User name : admu
    Password : new_pass
    MongoDB host : localhost
    MongoDB port : 27017
    Database : university
    */
    $server = "mongodb://admu:new_pass@localhost:27017/university";

    try{
        // Connecting to server
        $c = new MongoClient( $server );
    }catch(MongoConnectionException $connectionException){
        print $connectionException;
        exit;
    }

    // Data to be inserted
    $data = array(
        "name"=>"Mitra",
        "age"=>21,
        "gender"=>"M",
        "course"=>"BTECH",
        "marks"=>77
    );

    try{
        // Geting MongoDB
        $db = $c->university;

        // Getting MongoCollection
        $collection = $db->students;
    }catch(MongoException $mongoException){
        print $mongoException;
        exit;
    }

    try{
        // Inserting data into students collection
        $ret = $collection->insert($data);
    }catch(MongoCursorException $mongoCursorException){
        echo $mongoCursorException;
        exit;
    }

    if(is_array($ret)) {
        if($ret["ok"])
            echo "Document is inserted successfully";
        else
            echo "document insertion failed";
    }else {
        if($ret)
            echo "Document is inserted successfully";
        else
            echo "document insertion failed";
    }

    // Array of data to be inserted
    $data = array(
        array(
            "name"=>"Banerjee",
            "age"=>20,
            "gender"=>"M",
            "course"=>"BTECH",
            "marks"=>70
            ),
        array(
            "name"=>"Abdulla",
            "age"=>19,
            "gender"=>"M",
            "course"=>"BTECH",
            "marks"=>89
       )
    );
    try{
        // Inserting data into students collection
        $ret = $collection->batchInsert($data);
    }catch(MongoCursorException $mongoCursorException){
        echo $mongoCursorException;
        exit;
    }
    if(is_array($ret)) {
        if($ret["ok"])
            echo "<br />Batch insertion success";
        else
            echo "<br />Batch insertion failed";
    }else {
        if($ret)
            echo "<br />Batch insertion success";
        else
            echo "<br />Batch insertion failed";
        }

Open the above created php file “students_insert.php” with its url in a web browser

A php program to insert data into MongoDB database

Figure 1 : A php program to insert data into MongoDB database


Documents available in “students” collection after executing php program

> db.students.find()
{ "_id" : ObjectId("50d69d6a1d26a8a0c1eaecf8"), "name" : "Rajesh", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 81 }
{ "_id" : ObjectId("50d69de81d26a8a0c1eaecf9"), "name" : "John", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 79 }
{ "_id" : ObjectId("50d69e5bbe5a399f4650f9a3"), "name" : "Firoz", "age" : 22, "gender" : "M", "course" : "BTECH", "marks" : 88 }
{ "_id" : ObjectId("50d69e5bbe5a399f4650f9a4"), "name" : "Alan", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 68 }
{ "_id" : ObjectId("50d69eb8be5a399f4650f9a5"), "name" : "Anjali", "age" : 20, "gender" : "F", "course" : "MBA", "marks" : 67 }
{ "_id" : ObjectId("50d69eb8be5a399f4650f9a6"), "name" : "Ali Khan", "age" : 20, "gender" : "M", "course" : "MBA", "marks" : 59 }
{ "_id" : ObjectId("50da9cd697f0d88a05000000"), "name" : "Mitra", "age" : 21, "gender" : "M", "course" : "BTECH", "marks" : 77 }
{ "_id" : ObjectId("50da9cd697f0d88a05000001"), "name" : "Banerjee", "age" : 20, "gender" : "M", "course" : "BTECH", "marks" : 70 }
{ "_id" : ObjectId("50da9cd697f0d88a05000002"), "name" : "Abdulla", "age" : 19, "gender" : "M", "course" : "BTECH", "marks" : 89 }


Download php application


What is next?

A php program to retrieve MongoDB data is available at “A PHP program to fetch data from a collection in MongoDB database using cursors“.

A php program to update existing MongoDB data is available at “A PHP program to update collection data in MongoDB database with upsert option“.


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner