Search code examples
mongodbmongodb-querymongodb-indexes

unique index only if field exist


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?


Solution

  • 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