MongoDB无法创建唯一的稀疏索引(重复键) [英] MongoDB can not create unique sparse index (duplicate key)
问题描述
我想在两列上创建一个唯一索引,其中索引应为索引的第二部分允许多个空值.但是:
I want to create a unique index over two columns where the index should allow multiple null values for the second part of the index. But:
db.model.ensureIndex({userId : 1, name : 1},{unique : true, sparse : true});
引发重复键异常:E11000重复键错误索引:devmongo.model.$ userId_1_name_1 dup键:{:"-1",:null}.我认为由于sparse = true选项,索引应该允许这个星座吗?我怎样才能做到这一点?我使用MongoDB 2.6.5
Throws a duplicate key exception: E11000 duplicate key error index: devmongo.model.$userId_1_name_1 dup key: { : "-1", : null }. I thought because of the sparse=true option the index should allow this constellation? How can I achieve this? I use MongoDB 2.6.5
推荐答案
复合索引应视为一个整体,因此唯一要求(用户ID,名称)对在集合中必须唯一和 sparse (稀疏)表示如果文档中同时丢失了 userId 和 name ,则允许.错误消息显示至少有两个文档的(用户ID,名称)对等效(如果缺少字段,则该值可以视为null).
The compound index should be considered as a whole one, so unique requires (userId, name) pair must be unique in the collection, and sparse means if both userId and name missed in a document, it is allowed. The error message shows that there are at least two documents whose (userId, name) pairs are equivalent (if a field missed, the value can be considered as null).
这篇关于MongoDB无法创建唯一的稀疏索引(重复键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!