Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb 3.4.2 InvalidIndexSpecificationOption error: The field 'unique' is not valid for an _id index specification

The command db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} ) fails on mongo version 3.4.2, but not 3.2.11. The mongo documentation indicates the version 3.4 supports both the unique and background attributes.

Mongo 3.4.2 fails ...

> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
    "ok" : 0,
    "errmsg" : "The field 'unique' is not valid for an _id index specification. Specification: { ns: \"testDB.testCollection\", v: 1, key: { _id: 1.0 }, name: \"_id_2\", unique: true, background: true }",
    "code" : 197,
    "codeName" : "InvalidIndexSpecificationOption"
}
> 

Mongo 3.2.11 works ...

> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 1,
    "note" : "all indexes already exist",
    "ok" : 1
}
> 

Anyone know of a work around?

We're using the Mongoose Node.js wrapper to create the Mongo indexes, so not adding the unique and background attributes isn't an option.

Cheers!

Ed

like image 517
icedawn Avatar asked Feb 21 '17 21:02

icedawn


People also ask

How do I make a field unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What is unique index in MongoDB?

A unique index ensures that a given value can be stored only once for a given field. Whenever you create a collection in Mongo, a unique index is automatically created on the _id field. This is what ensures that no two documents with the same _id are stored.


1 Answers

That unique is not problem here.. It's that _id, what already have index (created automatically) and you cannot create second index what have exactly same fields (_id:1) what first one have.

How about testing with some other field than _id and you will find out that unique and background is possible, as long as that field don't have index already present.

like image 58
JJussi Avatar answered Oct 03 '22 18:10

JJussi