nkuhta
nkuhta

Reputation: 11128

MongoDB: duplicate documents in collection

I'm new in mongodb and can't find the solution.

I'm using mongo-php-driver

I just created some collection. I want to create some document from PHP code.

$collection->create(array(
    'asda'=>12312,
    'cxzcxz'=>'czczcxz'
));

When that code works, there are two same records in collection, with different _id.

{ "_id" : ObjectId("4ff4b3b8859183d41700000f"), "asda" : 12312, "cxzcxz" : "czczcxz" }
{ "_id" : ObjectId("4ff4b3b8859183d417000010"), "asda" : 12312, "cxzcxz" : "czczcxz" }

How to fix it, and what I need to change here to have only one document?

I have _id index in table. Maybe I need to set this key every time? When i setted _id field, it saved one record in collection. But how to make it auto (like auto increment) ?

Upvotes: 2

Views: 3769

Answers (1)

Stennie
Stennie

Reputation: 65323

You are able to insert more than one record with similar information because you have not specified a unique index on any of those values. The default unique index will be on _id.

You can define your own index from PHP using MongoCollection.ensureIndex eg:

// create a unique index on 'phonenum'
$collection->ensureIndex(array('phonenum' => 1), array("unique" => true));

It's also worth reading the MongoDB documentation on unique indexes as there are a few caveats to be aware of if a unique index is being created for an existing collection that may already have duplicates or null values.

You also have the option of providing your own _id value if there is a more natural primary key to use. You will have to ensure that this _id is unique for new insertions, though.

The default ObjectID created by MongoDB is designed to have a reasonably high probability of being unique when allocated.

Code example:

<?php

// Connect to MongoDB server
$mongo = new Mongo();

// Use database 'mydb' and collection 'mycoll'
$collection = $mongo->mydb->mycoll;

// Drop this collection for TESTING PURPOSES ONLY
$collection->drop();

// The document details to insert
$document = array(
    'asda' => 12312,
    'cxzcxz' => 'czczcxz',
);

try {
    $collection->insert($document, array("safe" => true));

    // Note that $collection->insert() adds the _id of the document inserted
    echo "Saved with _id:", $document['_id'], "\n";
}
catch (MongoCursorException $e) {
    echo "Error: " . $e->getMessage()."\n";
}

// Add unique index for field 'asda'
$collection->ensureIndex(array('asda' => 1), array("unique" => true));

// Try to insert the same document again
$document = array(
    'asda' => 12312,
    'cxzcxz' => 'czczcxz',
);
try {
    $collection->insert($document, array("safe" => true));
    echo "Saved with _id:", $document['_id'], "\n";
}
catch (MongoCursorException $e) {
    echo "Error: " . $e->getMessage()."\n";
}

?>

Upvotes: 4

Related Questions