If There is a unique index on a field A, then there cannot be 2 documents where A doesn't exist.
How do I specify that the uniqueness should only be enforced on documents where A actually exists?
Lets assume the following object in mongodb
[
{
"name": "A",
"phone": 787878
},
{
"name": "B",
"phone": 66446
},
{
"name": "C"
}
]
Now you want to make the phone
variable to be unique upon its existances. You can use the following, sparse: true
is responsible to check whether the variable is present or not
db.collection.createIndex({ phone: 1 }, { unique: true, sparse: true })