Search code examples
mongodbmongodb-indexes

Cannot create index - bad index key pattern


After some activities with my database, I lost my index. I had these indexes:

{
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "collection.statement"
},
{
    "v" : 1,
    "unique" : true,
    "key" : {
        "name" : 1
    },
    "name" : "name_1",
    "ns" : "collection.statement"
}

and now I have only first one. I've entered this command

db.collection.createIndex({
    "v" : 1, 
    "unique" : true, 
    "key" :{ "name" : 1 }, 
    "name" : "name_1", 
    "ns" : "collection.statement"
})

and I only get and error message that i have a bad index key pattern. Please, help me, how to return this index? What I do wrong?


Solution

  • Use this:

    db.collection.createIndex( { "name": 1 }, { unique: true } )
    

    You attempt includes internal aspects of the index ("v" : 1), you just need to supply the field(s) and an order for each and the unique instruction.

    More details in the docs.