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 }