Unique index in mongoDB 3.2 ignoring null values

前端 未结 4 1552
余生分开走
余生分开走 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:31

    You can create partial index in mongo:3.2. Example, if ipaddress can be "", but "127.0.0.1" should be unique. The solution can be like this:

    db.collectionName.createIndex(
     {"ipaddress":1},
     {"unique":true, "partialIndexExpression":{"ipaddress":{"$gt":""}}})
    

    This will ignore "" values in ipaddress filed and still be unique

提交回复
热议问题