Unique index in mongoDB 3.2 ignoring null values

前端 未结 4 1492
余生分开走
余生分开走 2021-02-07 00:24

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.

4条回答
  •  不思量自难忘°
    2021-02-07 00:29

    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.

提交回复
热议问题