【问题标题】:Mongo's bulkWrite with updateOne + upsert works the first time but gives duplicate key error subsequent timesMongo 的 bulkWrite with updateOne + upsert 第一次工作,但随后出现重复键错误
【发布时间】: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


【解决方案1】:

好的,我能够修复它。我相信这可能是一个错误,我已经在 Github 存储库中报告了它。

只有当“id”是一串数字时才会出现问题。一旦我将“id”(我正在索引的字段)转换为整数,它就可以完美地工作。

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多