问题
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 !!
Here are details :
> 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 !
回答1:
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});
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});
来源:https://stackoverflow.com/questions/8943418/ensure-index-not-working-mongodb