I\'m beginner with MongoDB and i\'m trying some stuff. I want to store URL and to avoid duplicate URL I create an unique index on the url. Like that
collection.c
You'll need to pass the unique value as the boolean value true, not as a string, and it's the second parameter that are options:
...ensureIndex(new BasicDBObject("url", 1), new BasicDBObject("unique", true));
Also, I tested it manually using the mongo interpreter:
> db.createCollection("sa")
{ "ok" : 1 }
> db.sa.ensureIndex({"url":1},{unique:true})
> db.sa.insert({url:"http://www.example.com", crawled: true})
> db.sa.insert({url:"http://www.example.com", crawled: true})
E11000 duplicate key error index: test.sa.$url_1 dup key: { : "http://www.example.com" }
> db.sa.insert({url:"http://www.example2.com/", crawled: false})
> db.sa.insert({url:"http://www.example.com", crawled: false})
E11000 duplicate key error index: test.sa.$url_1 dup key: { : "http://www.example.com" }
>
There are only the two objects:
> db.sa.find()
{ "_id" : ObjectId("50d636baa050939da1e4c53b"), "url" : "http://www.example.com", "crawled" : true }
{ "_id" : ObjectId("50d636dba050939da1e4c53d"), "url" : "http://www.example2.com/", "crawled" : false }
Just stumbled over this question and there are some changes since Version 3.0.0
db.collection.ensureIndex(keys, options)
Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex().
Creates an index on the specified field if the index does not already exist.
To Use the unique index of the mongodb, you should use the method with 2 parameters where 3rd boolean parameter is for the "unique" index.
mongo.getCollection().ensureIndex(new BasicDBObject("url", 1),"unq_url", true));
I don't fully understand your problem but I feel it's very likely that you should use ensureIndex
instead of createIndex
as the latter always tries to create the index while the former will only ensure that it exists.
Also I see that you dont have a collection name specified in getCollection();
What collection would that select? curious