0

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?

1 Answers1

1

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 })

query

result

data

error

  • What about compound indexes? The requirement is to index documents that only contain all fields in the compound index? According to https://www.mongodb.com/docs/manual/core/index-sparse/, it will index docs that contain at least one field – Bear Bile Farming is Torture Jul 24 '23 at 15:18