Mongodb-在现有集合上添加唯一索引 [英] Mongodb- Add unique index on an existing collection
本文介绍了Mongodb-在现有集合上添加唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Mongodb中学习索引.我创建了一个数据库和一个集合,如下所示:
I am trying to learn indexing in Mongodb. I created a database and a collection as follows:
use mydb
db.createCollection("myFirstCollection")
one={name:"Helios"}
two={name:"Kepler"}
db.myFirstCollection.insert(one)
db.myFirstCollection.insert(two)
我能够列出以下结果:
db.myFirstCollection.find()
{ "_id" : ObjectId("53cde256f8807057b6bd827b"), "name" : "Helios" }
{ "_id" : ObjectId("53cde25bf8807057b6bd827c"), "name" : "kepler" }
我想在字段name
上添加唯一索引.但是当我尝试时,出现以下错误
I want to add unique index on the field name
. But when I tried, got the following error
db.myFirstCollection.ensureIndex({name:1},{unique:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"ok" : 0,
"errmsg" : "E11000 duplicate key error index: mydb.myFirstCollection.$name_1 dup key: { : null }",
"code" : 11000
}
我无法弄清楚我在做什么.请帮忙.
I am unable to figure out the mistake what I am making. Please help.
推荐答案
请在此处查看缺少的字段部分: https://docs.mongodb.com/manual/core/index-unique/
Please see missing field section here: https://docs.mongodb.com/manual/core/index-unique/
您只能有一个不包含集合中存在的唯一索引的文档.
You can only have a single document that does not contain the unique index existing in the collection.
这篇关于Mongodb-在现有集合上添加唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文