I just learned something hard way today.
I have a collection, lets call it foo_collection. The data format of that collection is something like this:
{
file: "filename1",
started: "Sat Feb 20 2010 04:15:02 GMT-0500 (EST)",
ended: "Sat Feb 20 2010 04:15:04 GMT-0500 (EST)"
}
Initially, the key “file” is used as normal index
db.ensureIndex({file: 1});
Later on, I had to change the index from normal to unique. So, I did:
db.ensureIndex({file: 1}, {unique: true});
This didn’t work because, the collection already contained multiple similar values of file key. And MongoDB console also doesn’t show any error or any message when the above command is run.
It should have been:
db.ensureIndex({file: 1}, {unique: true, dropDups: true});
Again, it should be noted that the above command will delete all the duplicate entries with the indexed key. So, use with caution.
I know this was kind of childish mistake but wanted to share so, someone reading this post won’t repeat it again.
Update: You can also check if db.ensureIndex() is working or not by calling db.getLastError() and you can also do the same from driver level by setting “safe” option. (Credit: Kristina)