Add field that is unique index to collection in MongoDB
我正在尝试将用户名字段添加到"用户"集合中的文档中,我希望它是唯一索引。 (到目前为止,我们一直在使用电子邮件地址登录,但我们也想添加一个用户名字段。)但是,运行db.users.ensureIndex({username:1},{unique:true})失败是因为mongo认为所有未设置的用户名都是重复的,因此不是唯一的。有人知道如何解决这个问题吗?
显示当前用户和用户名(如果有):
1 2 3 4 | > db.users.find({},{_id:0,display_name:1,username:1}) {"display_name" :"james" } {"display_name" :"sammy","username" :"sammy" } {"display_name" :"patrick" } |
尝试使"用户名"字段成为唯一索引:
1 2 3 4 5 6 7 8 | > db.users.ensureIndex({username:1},{unique:true}) { "err" :"E11000 duplicate key error index: blend-db1.users.$username_1 dup key: { : null }", "code" : 11000, "n" : 0, "connectionId" : 272, "ok" : 1 } |
它不起作用,因为
让我们将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | > db.users.update({display_name: 'patrick'}, { $set: {username: 'patrick'}}); > db.users.ensureIndex({username:1},{unique:true}) > db.users.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" :"blend-db1.users", "name" :"_id_" }, { "v" : 1, "key" : { "username" : 1 }, "unique" : true, "ns" :"blend-db1.users", "name" :"username_1" } ] |
现在可以使用了!
为澄清这个问题,我想要的是能够使
尝试创建唯一的稀疏索引:
1 | db.users.ensureIndex({username:1},{unique:true,sparse:true}) |
根据文档:
You can combine the sparse index option with the unique indexes option
so that mongod will reject documents that have duplicate values for a
field, but that ignore documents that do not have the key.
尽管这仅适用于不具有该字段的文档,而不适用于具有该字段但文档的字段具有