Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique index in mongoDB 3.2 ignoring null values

I want to add the unique index to a field ignoring null values in the unique indexed field and ignoring the documents that are filtered based on partialFilterExpression.

The problem is Sparse indexes can't be used with the Partial index.

Also, adding unique indexes, adds the null value to the index key field and hence the documents can't be ignored based on $exist criteria in the PartialFilterExpression.

Is it possible in MongoDB 3.2 to get around this situation?

like image 386
Nikhil Avatar asked Mar 02 '16 18:03

Nikhil


People also ask

Can unique index have null values?

Therefore, unique indexes do not enforce primary key constraints by themselves because they allow null values.

Does MongoDB support unique indexes?

Starting in MongoDB 5.0, unique sparse and unique non-sparse indexes with the same key pattern can exist on a single collection.

How does MongoDB store unique data?

To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.

Does MongoDB store null value?

Indeed, it's not possible to store null values in a MongoDB document using a DataFrame. The Python None values are considered as missing attributes accordingly to this NoSQL specific allowance. However, if your column is numerical, you can force writing a null value by setting it to NaN.


2 Answers

I am adding this answer as I was looking for a solution and didn't find one. This may not answer exactly this question or may be, but will help lot of others out there like me.

Example. If the field with null is houseName and it is of type string, the solution can be like this

db.collectionName.createIndex(    {name: 1, houseName: 1},    {unique: true, partialFilterExpression: {houseName: {$type: "string"}}} ); 

This will ignore the null values in the field houseName and still be unique.

like image 95
mythicalcoder Avatar answered Oct 21 '22 15:10

mythicalcoder


Yes, you can create partial index in MongoDB 3.2

Please see https://docs.mongodb.org/manual/core/index-partial/#index-type-partial

MongoDB recommend usage of partial index over sparse index. I'll suggest you to drop your sparse index in favor of partial index.

like image 30
Saleem Avatar answered Oct 21 '22 15:10

Saleem