Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7684

MongoDB create unique field but not indexed?

Is there any option by which in Mongo I can make the field as unique, but do not index it, because as every index occupies some space as well as causes an overhead on each insert, update and delete, and as I am rarely going to use this field for read operations, that's why I only want to restrict uniqueness but do not want any performance gain by using indexing.

Upvotes: 2

Views: 1032

Answers (2)

Cuong Vu
Cuong Vu

Reputation: 3733

As far as I know, there's no way and no reason to do that. What do you mean by

overhead on each insert, update and delete

That overhead comes from unique constraint, not because of the indexes.

every index occupies some space

Yeah, of course, it takes some space to store indexes in HDD or SSD, but as long as you don't do read/query, it will not affect the performance of another operations.

Read more: MongoDB Internal implementation of indexing ?

Upvotes: 3

kevinadi
kevinadi

Reputation: 13795

Alternatively, you can use a custom value for the _id field, which is:

  • required to be present in every document
  • required to have a unique value within a collection
  • indexed by default

In the Field Names section:

The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

If you don't provide an _id field when you insert a document, MongoDB will create one for you using ObjectId.

If your requirement mandates the use of a unique constraint and you don't want to create an extra index to enforce uniqueness, just use the _id field.

Upvotes: 1

Related Questions