Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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
like image 400
mark Avatar asked Jan 02 '13 14:01

mark


2 Answers

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.

like image 195
muruga Avatar answered Sep 19 '22 06:09

muruga


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.

like image 28
coderLMN Avatar answered Sep 18 '22 06:09

coderLMN