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) ?
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:
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
_idvalue if there is a more natural primary key to use. You will have to ensure that this_idis 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: