How to create a mongo index to ensure a field is never null/absent/empty?

mongodb

Solution

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.

Problem

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 ```

Original source