繁体   English   中英

MongoDB 唯一索引不起作用

[英]MongoDB unique index is not working

我正在使用 Java 中的 Mongodb。

我创建了一个集合和一个这样的索引:

collection = mongoClient.getDB(DB_NAME).getCollection(COLLECTION_NAME)
collection.ensureIndex(new BasicDBObject(['customerReference': 1, 'unique': true]))

当我检查 mongo shell 时,我看到:

{ 
   "v" : 1, 
   "key" : { "customerReference" : 1, "unique" : true }, 
   "ns" : "diagnostics.diagnosticData", 
    "name" : "customerReference_1_unique_" 
}

但我仍然可以插入重复项:

{ 
  "_id" : ObjectId("52f3ba8a7d841c01680e0bc5"), 
  "customerReference" : 3, 
  "data" : "original data", 
  "created" : ISODate("2014-02-06T16:38:34.191Z") 
}
{ 
  "_id" : ObjectId("52f3ba8a7d841c01680e0bc6"), 
  "customerReference" : 3, 
  "data" : "duplicate data", 
  "created" : ISODate("2014-02-06T16:38:34.194Z") 
}

为什么?

可能您没有正确创建索引。

通过执行以下语句从 DB shell 执行此操作:

db.refs.ensureIndex({customerReference: 1}, {unique : true})

在这里,当我尝试使用重复的customerReference插入文档时,我收到一个错误,说:

E11000 重复键错误索引:test.refs.$customerReference_1 重复键:{ : 3.0 }

当我执行db.refs.getIndexes()命令时,我得到:

{
    "v" : 1,
    "key" : {
        "customerReference" : 1
     },
     "unique" : true,
     "ns" : "test.refs",
     "name" : "customerReference_1"
 }

这表明唯一索引已正确创建,但与您的略有不同。

更新:当您确保集合中的索引时,您制作了一个BasicDBObject ,这将导致:

"key" : { "customerReference" : 1, "unique" : true }

此处, key的值不应包含unique属性。

unique属性应该放在index文档中,就像在我的代码中一样:

"key" : {
     "customerReference" : 1
 },
 "unique" : true

要正确创建索引,您必须提供两个BasicDBObjects

  • 一个{customerReference : 1}
  • 一个为{unique : true}

我在 JavaScript 中使用 mongoose,但我认为我发现的解决方案也适用于其他语言......当您将数据库与应用程序连接时,添加此选项:“audoIndex: true”,例如在 JS 中像这样:

const options = {
// your options go here
...
// this code is the solution
audoIndex: true
}
mongoose.connect(DB_URI, options);

我还删除了我有问题的集合并重新创建它以确保它可以工作。 我在以下位置找到了这个解决方案: https : //dev.to/emmysteven/solved-mongoose-unique-index-not-working-45d5我也尝试过诸如“重启 MongoDB”之类的解决方案,但对我不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM