php - MongoDB:集合中的重复文档

标签 php mongodb

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

我正在使用mongo-php-driver

我刚刚创建了一些集合。 我想从 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 字段时,它在集合中保存了一条记录。但如何使其自动(如自动增量)?

最佳答案

您可以插入多个具有相似信息的记录,因为您没有为这些值中的任何一个指定唯一索引。 default unique index将在 _id 上。

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

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

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

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

默认ObjectID由 MongoDB 创建的设计旨在在分配时具有相当高的唯一性概率。

代码示例:

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

?>

关于php - MongoDB:集合中的重复文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11335665/

相关文章:

javascript - 从 AJAX 和 PHP 加载数据时如何将数据存储在缓存中

php - 在 Magento 中调用辅助类

php - 格式化 mysqlquery 中创建的字段

php - 通过php导入excel文件到mysql数据库

json - MongoDB 中的 Map/Reduce 任务 : Aggregation of nested objects

grails - GORM mongodb 映射到现有集合结构

c# - 如何处理 JSON 以从字段名称中删除句点?

javascript - node.js - 在 mongodb 单元测试上应用 sinon

php - 在外部 API 调用上将 PhpStorm 连接到 Xdebug

javascript - node.js:Mongodb db.collection.find() 在 collection.insert 工作时不工作