upsert 期间出现重复键错误 [解释]

发布于 2024-12-19 00:57:07 字数 450 浏览 2 评论 0原文

我正在类中执行以下语句。这段代码来自

$query  = array('_id' => $id, 'lock' => 0);
$update = array('$set' => array('lock' => 1));
$options = array('safe' => true, 'upsert' => true);
$result = $this->_mongo->update($query, $update, $options);

if ($result['ok'] == 1) {
    return true; 
}

但是我不明白如何得到重复的键错误。 有人可以解释一下我收到此错误的可能情况和可能性吗?

我一直在广泛研究这个问题,但在任何地方都找不到答案。因此,如果它在 SO 或任何其他网站上,请分享!

提前致谢。

I am executing the below statement in a class. This code is from

$query  = array('_id' => $id, 'lock' => 0);
$update = array('$set' => array('lock' => 1));
$options = array('safe' => true, 'upsert' => true);
$result = $this->_mongo->update($query, $update, $options);

if ($result['ok'] == 1) {
    return true; 
}

However I do not understand how I would get a duplicate key error.
Can someone explain the possible scenarios and likelihood that I will receive this error?

I have been researching this extensively, cannot find my answer anywhere. So if it is on SO or any other website please share!

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白芷 2024-12-26 00:57:07

由于您正在进行更新插入并在查询中包含 _id,因此您不应该在该键上获得任何重复项。这让我认为您已经在 lock 上创建了一个唯一索引,该索引不适用于 2 个以上的文档,因为该字段只有 2 个值。

如果您尚未锁定唯一索引,则您必须在此处未显示的字段上拥有唯一索引。这也不起作用,因为在插入时,您的 upsert 将仅设置 _idlock,任何其他具有索引的字段将被插入为 null。如果这些字段之一具有唯一索引,则只有单个文档在该字段中可以具有 null。因此,当您尝试为该字段插入另一个 null 时,您将收到重复键错误。

Since you're doing an upsert and including _id in your query, you shouldn't be getting any duplicates on that key. This makes me think that you've created a unique index on lock, which isn't going to work for more than 2 documents because you only have 2 values for that field.

If you haven't put a unique index on lock, then you must have a unique index on a field you aren't showing here. That won't work either because on an insert, your upsert is going to set _id and lock only, any other field with an index will be inserted as null. If one of those fields has a unique index, then only a single document can have a null in that field. So when you try and insert another null for that field, you'll get a duplicate key error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文