MongoDB:集合中的重复文档


MongoDB: duplicate documents in collection

我是mongodb的新手,找不到解决方案。

我正在使用 mongo-php 驱动程序

我刚刚创建了一些集合。我想从PHP代码创建一些文档。

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

当该代码起作用时,集合中有两个相同的记录,具有不同的_id。

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

如何解决它,以及我需要在这里更改什么以只有一个文档?

我在表中有_id索引。也许我每次都需要设置这个键?当我设置_id字段时,它在集合中保存了一条记录。但是如何使它自动(如自动增量)?

您可以插入多个具有类似信息的记录,因为您尚未对其中任何值指定唯一索引。 默认的唯一索引将在 _id 上。

您可以使用MongoCollection.ensureIndex从PHP定义自己的索引,例如:

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

还值得阅读有关唯一索引的MongoDB文档,因为如果为可能已经具有重复或空值的现有集合创建唯一索引,则需要注意一些注意事项。

如果可以使用更自然的主键,还可以选择提供自己的_id值。 但是,您必须确保此_id对于新插入是唯一的。

MongoDB创建的默认ObjectID被设计为在分配时具有相当高的概率是唯一的。

代码示例:

<?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";
}
?>