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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

What about compound indexes? The requirement is to index documents that only contain all fields in the compound index? According to mongodb.com/docs/manual/core/index-sparse, it will index docs that contain at least one field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.