Create an index with MongoDb

前端 未结 5 1724
春和景丽
春和景丽 2021-02-13 03:20

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         


        
相关标签:
5条回答
  • 2021-02-13 04:02

    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 }
    
    0 讨论(0)
  • 2021-02-13 04:04

    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.

    0 讨论(0)
  • 2021-02-13 04:10

    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));

    0 讨论(0)
  • 2021-02-13 04:24

    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.

    0 讨论(0)
  • 2021-02-13 04:26

    Also I see that you dont have a collection name specified in getCollection();

    What collection would that select? curious

    0 讨论(0)
提交回复
热议问题