【发布时间】:2020-07-25 17:49:54
【问题描述】:
我正在使用 Mongo-php-library 将许多文档插入到我的集合中(使用 bulkWrite)。如果文档已经存在,我希望更新文档,如果不存在则插入文档,所以我使用“upsert = true”。
代码在我第一次运行时运行良好(它会插入文档),但第二次运行时却出现此错误:
Fatal error: Uncaught MongoDB\Driver\Exception\BulkWriteException: E11000 duplicate key error collection: accounts.posts index: postid dup key: { id: "2338...
我看不出我的代码有什么问题。我已经浏览了所有 SO 帖子,但没有任何帮助。
这是我的代码:
// I prepare the array $post_operations with all updateOne operations
// where $data is an object that contains all the document elements I want to insert
$posts_operations = array();
foreach ($this->posts as $id => $data) {
array_push($posts_operations, array('updateOne' => [['id' => $id], ['$set' => $data], ['upsert' => true]]));
}
// Then I execute the method bulkWrite to run all the updateOne operations
$insertPosts = $account_posts->bulkWrite($posts_operations);
第一次可以正常工作(插入时),但第二次就不行了(应该更新时)。
我在集合中为“id”设置了唯一索引。
非常感谢您的帮助。
【问题讨论】:
-
id 已经有唯一索引了,你不需要自己做。而且违反的索引是postid而不是id。
-
感谢@D.SM,但我为“id”而不是“_id”创建了一个索引。它们是不同的。
-
“postid”是字段“id”(不是“_id”)的唯一索引
标签: mongodb mongodb-query mongodb-php