I am trying to import a csv file into a mongodb collection, I have seen that it can be done through the mongoimport command, however I need to do it through php because I want to validate the entered data afterwards. So far I have managed to open the file and put its contents in columns as shown:
public function storeCSV($upcsv, $coll) {
if(($gestor = fopen($upcsv, "r")) !== FALSE){
$cont=0;
$array = array();
while (!feof($gestor)){
$datos = fgetcsv($gestor, 1000, ",");
if($cont > 0){
$array = [
"Matricula" => $datos[0],
"Nombre" => $datos[1],
"Edad" => $datos[2]
];
var_dump($array);
}
$cont++;
$coll->insertOne($array);
}
fclose($gestor);
echo "Importacion completada";
}
else{
echo "Archivo no encontrado";
}
}
The result is the following:
array(3) {
["Matricula"]=>
string(3) "001"
["Nombre"]=>
string(4) "Juan"
["Edad"]=>
string(2) "20"
}
array(3) {
["Matricula"]=>
string(3) "002"
["Nombre"]=>
string(5) "Maria"
["Edad"]=>
string(2) "20"
}
array(3) {
["Matricula"]=>
string(3) "003"
["Nombre"]=>
string(6) "Carlos"
["Edad"]=>
string(2) "21"
}
or its equivalent:
"Matricula","Nombre","Edad"
"001","Juan","20"
"002","Maria","20"
"003","Carlos","21"
Now I want that data to be entered into a collection in mongodb, for this I use the insert () method as it is shown in the code, but when executing it, it tells me that it can not use that method, I have already created a connection to mongo so I do not understand why it does not work. I've also tried with insertOne () and insertMany (), but it's the same.
Greetings and thanks in advance.