I am trying to migrate data from mysql to mongo. It adds one record fine to mongo but then on the second record I am getting
Fatal error: Uncaught exception 'MongoDuplicateKeyException' with message 'localhost:27017: E11000 duplicate key error index: app.hospitals.$_id_ dup key: { : ObjectId('558365d7423467484bd63af3') }'
Not sure what I am doing wrong
here is my code
<?php
//echo phpinfo();
$host = "localhost";
$user = "root";
$password = "root";
$database = "database";
// Create connection
$conn = new mysqli($host, $user, $password, $database);
$connection = new MongoClient();
$db = $connection->database;
$collection = $db->hospitals;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM hospitals";
if($result = $conn->query($sql)){
$i=0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$value){
$collection->insert($row);
unset($collection->_id);
}
if($i > 3) die;
$i++;
}
}
$conn->close();
?>
using
instead of insert solved the issue. Not sure why though.