Take the 2-minute tour ×

I have a field in an entity, which must be present, but not necessarily unique. Is there a way to enforce this constraint in Mongo?

I understand that mongo collections are schemaless and the only schema a collection can have is the index schema. But I do not see if there is an index option to make sure a field value is not empty, where an empty field value satisfies the following javascript expression:

!value && value !== 0 && value !== false
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Only on the UNIQUE index, you can kind of mock this. You can create a document with an entry with the field / value missing and it will create the document with the NULL value in the index and WILL NOT allow further missing values.

Since your requirement is for NON UNIQUE key, I don't think that you have an option at this point in MONGODB (v2.2) to ensure that the values have to be present on the indexed column.

share|improve this answer
add comment

In mongodb, only the _id field can meet your requirement. Indexing does not seem to be a good idea (neither a feasible one) for this issue.

I think you have to enforce this rule in the insert and update operation in your app rather than asking mongodb to watch it for you.

share|improve this answer
add comment

Your Answer


