Home > Back-end >  Creation of Unique Index not working using Mongo shell
Creation of Unique Index not working using Mongo shell

Time:01-07

I have created small mongodb database, I wanted to create username column as unique. So I used createIndex() command to create index for that column with UNIQUE property.

I tried creating unique index using below command in Mongosh.

db.users.createIndex({'username':'text'},{unqiue:true,dropDups: true})

For checking current index, I used getIndex() command. below is the output for that.

newdb> db.users.getIndexes()
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  {
    v: 2,
    key: { _fts: 'text', _ftsx: 1 },
    name: 'username_text',
    weights: { username: 1 },
    default_language: 'english',
    language_override: 'language',
    textIndexVersion: 3
  }
]

Now Index is created, so for confirmation I checked same in MongoDB Compass.But I am not able to see UNIQUE property got assign to my newly created index. Please refer below screenshot. MongoDB Screenshot

I tried deleting old index, as it was not showing UNIQUE property and Created again using MongoDB Compass GUI, and now I can see UNIQUE Property assign to index. MongoDB Screentshot2 And below is output for getIndex() command in Mongosh.

newdb> db.users.getIndexes()
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  {
    v: 2,
    key: { _fts: 'text', _ftsx: 1 },
    name: 'username_text',
    unique: true,
    sparse: false,
    weights: { username: 1 },
    default_language: 'english',
    language_override: 'language',
    textIndexVersion: 3
  }
]

I tried searching similar topics, but didn't found anything related. Is there anything I am missing or doing wrong here?

CodePudding user response:

Misspelled the property unique as unqiue, which leads to this issue. I tried again with the correct spelling, and it is working now. Sorry for a dumb question

  • Related