开发者

MongoDB _id Field Auto Generation?

I am trying to setup mongodb to test out its speed and am running into a issue with _id duplication. I am not setting the is, I am letting mongodb do as I don't care. I ahve the following php code:

<?php
$mongo = new Mongo();
$db = $mongo-&g开发者_如何学Ct;selectDB("scrap_fighters");
$collection = $db->selectCollection('scores');

$data = array
(
  'user_id' => 1,
  'name' => 'John Doe',
  'score' => 120
);

$start = microtime(true);
for($x=0; $x < 1000; $x++)
{
  $data['unqiue'] = microtime();
  $result = $collection->insert($data, array('safe' => true));
}
?>

What does mongodb use to generate thier "unique" ids? I even tried replacing unique with:

$data['unqiue'] = rand(1, 1000000);

To be 100% sure it was working but it still failed after the first write. can I not enter records with the same data without specific generation a unique id myself?


MongoDB uses _id as primary key, and as such it has to be unique. Since you don't specify it, it will automatically generated. It consists of a microsecond timestamp and a hash based on the host, so even there are multiple hosts inserting simultaneously the probabily of collision is extremely low.

What is this unique field you are using? If you wanted it to be a primary key just don't set it.

About failing on duplicates: the only reason I can think of this happening is that you previously set up an index on this collection which requires some field (or combination of fields) to be unique. If not needed, remove it. If it's valid (eg: the user_id has to be unique) then insert unique records.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜