MongoDB Indexes Unique Index


Example

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

enforce uniqueness on the defined index (either single or compound). Building the index will fail if the collection already contains duplicate values; the indexing will fail also with multiple entries missing the field (since they will all be indexed with the value null) unless sparse: true is specified.