db.members.createIndex( { "user_id": 1 }, { unique: true } ) By default, unique is false on MongoDB indexes. If you use the unique constraint on a compound index (page 489), then MongoDB will enforce uniqueness on the combination of values rather than the individual value for any or all values of the key. Unique Constraint Across Separate Documents The unique constraint applies to separate documents in the col- lection. That is, the unique index prevents separate documents from having the same value for the indexed key, but the index does not prevent a document from having multiple elements or embedded documents in an indexed array from having the same value. In the case of a single document with repeating values, the repeated value is inserted into the index only once. For example, a collection has a unique index on a.b : db.collection.createIndex( { "a.b": 1 }, { unique: true } ) The unique index permits the insertion of the following document into the collection if no other document in the collection has the a.b value of 5 : db.collection.insert( { a: [ { b: 5 }, { b: 5 } ] } ) Unique Index and Missing Field If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. Behavior MongoDB Documentation, Release 3.0.4 You can combine the unique constraint with the sparse index (page 505) to filter these null values from the unique index and avoid the error. Restrictions You may not specify a unique constraint on a hashed index (page 502). Create a Unique Index (page 519) See also: Sparse Indexes Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field. The index is “sparse” because it does not include all documents of a collection. By contrast, non-sparse indexes contain all documents in a collection, storing null values for those documents that do not contain the indexed field. To create a sparse index, use the db.collection.createIndex() method with the sparse option set to true . For example, the following operation in the mongo shell creates a sparse index on the xmpp_id field of the addresses collection: db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } ) Note: Do not confuse sparse indexes in MongoDB with block-level 3 indexes in other databases. Think of them as dense indexes with a specific filter. $^{3}$http://en.wikipedia.org/wiki/Database_index#Sparse_index 505 8.2. Index Concepts