upsert 期间出现重复键错误 [解释]
我正在类中执行以下语句。这段代码来自
$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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您正在进行更新插入并在查询中包含
_id
,因此您不应该在该键上获得任何重复项。这让我认为您已经在lock
上创建了一个唯一索引,该索引不适用于 2 个以上的文档,因为该字段只有 2 个值。如果您尚未锁定唯一索引,则您必须在此处未显示的字段上拥有唯一索引。这也不起作用,因为在插入时,您的 upsert 将仅设置
_id
和lock
,任何其他具有索引的字段将被插入为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 onlock
, 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
andlock
only, any other field with an index will be inserted asnull
. If one of those fields has a unique index, then only a single document can have anull
in that field. So when you try and insert anothernull
for that field, you'll get a duplicate key error.