确保索引不起作用 - MongoDB [英] Ensure index not working - MongoDB
问题描述
我正在尝试确保文档字段的索引,而不是
工作。 MongoDB版本是2.0.2。
这是非常基本的,不知怎的,我觉得我可能错过了
的东西或不!
能够插入3个带有相同空字符串的文档!!
I am trying to ensure index on a field of a document and its not working. MongoDB version is 2.0.2. This is very basic and somehow i'm feeling i might have missed something or not!!! Its able to insert 3 docs with same empty string !!
以下是详细信息:
> use testinsert
switched to db testinsert
> db.users.ensureIndex({ name : 1});
> doc = {
... name : ""
... }
{ "name" : "" }
> doc
{ "name" : "" }
> db.users.stats();
{
"ns" : "testinsert.users",
"count" : 0,
"size" : 0,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 2,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"flags" : 1,
"totalIndexSize" : 16352,
"indexSizes" : {
"_id_" : 8176,
"name_1" : 8176
},
"ok" : 1
}
> db.users.insert(doc);
> db.users.insert(doc);
> db.users.insert(doc);
> db.users.find();
{ "_id" : ObjectId("4f1980dc7e154e6702c4914c"), "name" : "" }
{ "_id" : ObjectId("4f1980dd7e154e6702c4914d"), "name" : "" }
{ "_id" : ObjectId("4f1980dd7e154e6702c4914e"), "name" : "" }
> db.users.ensureIndex({ name : 1});
> db.users.insert(doc);
> db
testinsert
> db.users.find();
{ "_id" : ObjectId("4f1980dc7e154e6702c4914c"), "name" : "" }
{ "_id" : ObjectId("4f1980dd7e154e6702c4914d"), "name" : "" }
{ "_id" : ObjectId("4f1980dd7e154e6702c4914e"), "name" : "" }
{ "_id" : ObjectId("4f1981557e154e6702c49150"), "name" : "" }
> version();
version: 2.0.2
有人可以澄清可能是什么问题!
can somebody pls clarify as to what might be the problem !
推荐答案
没有问题,你可以看到索引在那里。你期望它不允许重复元素?为此,您必须将唯一标志设置为true:
There are no problems, you can see that the index is there. You're expecting it not to allow duplicate elements? For that you have to set unique flag to true:
db.users.ensureIndex({ name : 1},{unique: true});
更新:使用 {unique:true}再次运行确保
不起作用,你必须再次放弃 ensureIndex
:
UPDATE: running ensure once again with {unique: true}
doesn't work, you have to drop and ensureIndex
again:
db.users.dropIndex({name:1})
db.users.ensureIndex({ name : 1}, {unique:true, dropDups : true});
这篇关于确保索引不起作用 - MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!