How do i upload a csv file to mongodb using phpSolutionAnswe

How do i upload a csv file to mongodb using php?

Solution

Answer:

<!-- MongoDB has a command named mongoimport which can be used to directly upload a CSV file into a particular collection of

a database with the first line of the csv as the keys and the following rest of the csv as the values for the respective keys

The format of mongoimport is as folllows

\"mongoimport --db database_name --collection collection_name --file csv_file_name --type csv\"

now we can use variables to store our database and collection\'s name.

we upload the file to get the filename and it\'s path and then simple substitute the database_name and collection_name etc

with our variables and run the command through shell via php by using the exec function of php-->

<?php

    //Your Database Connection include file here.

    //This Entire PHP part can be placed in a seperate action file

    if(isset($_POST[\'submit\']))

    {

        //Upload Directory path.

        $uploaddir = \'uploads/\';

        //FilePath with File name.

        $uploadfile = $uploaddir . basename($_FILES[\"file\"][\"name\"]);

        //Check if uploaded file is CSV and not any other format.

        if (($_FILES[\"file\"][\"type\"] == \"text/csv\")){

            //Move uploaded file to our Uploads folder.

            if (move_uploaded_file($_FILES[\"file\"][\"tmp_name\"], $uploadfile))

            {

                 //Import uploaded file to Database. $collection is defined in the connection file or can be defined here too

                 $command = \"mongoimport --db joins --collection \" . $collection . \" --file \" . $uploadfile .\" --type csv --headerline\" ;

               

                shell_exec($command);

            }

        }

        else{

            echo \"Please Upload a CSV file Only!\";

        }

    }

       

?>

                    <!--Simple Form(no css) to Upload the File-->

<html>

    <head>

        <form action=\'#\' method=\'post\' enctype=\'multipart/form-data\'>

        Choose file to import:<br><br>

        <input type=\'file\' name=\'file\' id=\'file\'><br><br>

        <input type=\'submit\' name=\'submit\' value=\'extract\'></form>

    </head>

</html>

How do i upload a csv file to mongodb using php?SolutionAnswer: <!-- MongoDB has a command named mongoimport which can be used to directly upload a CSV file
How do i upload a csv file to mongodb using php?SolutionAnswer: <!-- MongoDB has a command named mongoimport which can be used to directly upload a CSV file

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site