'MongoDB unique index with missing/null field

How can I define a unique index that achieves the following goal:

If name field is missing (or null), allow only one document with the same id, but if the name exists, allow multiple instances of it as long as (id,name) is unique.

Good

{
    "id" : "a",
    "name" : "John"
},
{
    "id" : "a",
    "name" : "Hugo"
}

Good

{
    "id" : "a"
}

Bad

{
    "id" : "a",
    "name" : "John"
},
{
    "id" : "a",
    "name" : "John"
}

Bad

{
    "id" : "a",
}
{
    "id" : "a",
    "name" : "John"
}


Solution 1:[1]

Conditional indexes can be implemented with Partial indexes.

If I get the requirement it's just these 2 indexes:

  {
    "name": "id_idx",
    "key": {
      "id": 1
    },
    "partialFilterExpression": {
      "name": null
    },
    "unique": true
  },
  {
    "name": "id_name_idx",
    "key": {
      "id": 1,
      "name": 1
    },
    "partialFilterExpression": {
      "name": {
        "$gt": ""
      }
    },
    "unique": true
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Blex