May 10 2010
Ensure Index in MongoDB
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)

7 Responses to “Ensure Index in MongoDB”



[...] Ensure Index in MongoDB | Prajwal Tuladhar’s Blog prajwal-tuladhar.net.np/2010/05/10/559/ensure-index-in-mongodb – view page – cached 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 Tweets about this link Topsy.Data.Twitter.User['infynyxx'] = {“photo”:”http://a1.twimg.com/profile_images/839249908/serious_normal.jpg”,”url”:”http://twitter.com/infynyxx”,”nick”:”infynyxx”}; infynyxxInfluential: “Blogged: Ensure Index in MongoDB http://bit.ly/bYkmsm ” 22 minutes ago view tweet retweet Filter tweets [...]
You can also call db.getLastError() after ensureIndex to make sure it worked. In the drivers there's a “safe” option that does the same thing.
Thanks for the info; I updated my post.
Thank you very much for sharing!!To top!louis vuitton outlet is a professional webside which offer lots of common sense of life and I have learnt a lot since my friends recommended it to me.There are several articles about this theme in Louis vuitton bags,come on and have a discussion! air jordan 7
compared to mysql, it is achivement. Mysql only complains there are duplications, you need to find and eliminate. I liked how mongoDb behaves.
compared to mysql, it is achivement. Mysql only complains there are duplications, you need to find and eliminate. I liked how mongoDb behaves.
Thanks for posting this! i really had good time reading this.