mark
mark

Reputation: 62896

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

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

Upvotes: 10

Views: 7904

Answers (3)

Polv
Polv

Reputation: 2208

This might be the answer you wanted (in Java/Kotlin):

    col.createIndex(Document("note", 2), IndexOptions()
            .partialFilterExpression(Filters.and(
                    Filters.gt("note", ""),
                    Filters.exists("note")))

Upvotes: 0

coderLMN
coderLMN

Reputation: 3076

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.

Upvotes: 3

muruga
muruga

Reputation: 1073

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.

Upvotes: 6

Related Questions