php mongo Uncaught exception 'MongoDuplicateKeyException' E11000

1.2k views Asked by At

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();

?>
2

There are 2 answers

0
Asim Zaidi On

using

$collection->save($row);

instead of insert solved the issue. Not sure why though.

0
Abido On

Had the same problem, I believe it's a problem with the PHP mongodb driver that it is not generating a new id inside the loop.
The weird part that the first time I called the script it inserted all the documents then the exception popped in the end, then when I dropped the database and called the script again, it only inserted one document before giving the exception.
Anyway I solved after reading this answer by explicitly assigning new id.

In your case, add this before the insert:

$row['_id'] = new MongoId();