0

I need an index that will provide me uniqueness of the field among all fields. For example, I have the document:

{
   _id: ObjectId("123"),
   fieldA: "a",
   fieldB: "b"
}

and I want to forbid insert the document

{
   _id: ObjectId("456"),
   fieldA: "new value for field a",
   fieldB: "a"
}

because already exists the document that has the value "a" set on field "fieldA". Is it possible?

user
  • 4,410
  • 16
  • 57
  • 83

1 Answers1

0

It seems you need a multikey index with a unique constraint. Take into account that you can only have one multikey index in each collection for this reason you have to include all the fields you like to uniqueness inside an array

{
   _id: ObjectId("123"),
   multikey: [
              {fieldA: "a"},
              {fieldB: "b"}
             ]
}

Give a try to this code

db.collection.createIndex( { "multikey": 1}, { unique: true } )

To query you have to code

db.collection.findOne({"multikey.fieldA": "a"},    // Query
   {"multikey.fieldA": 1, "multikey.fieldB": 1})   // Projection

For more info you can take a look at embedded multikey documents.

Hope this helps.

another option is to create a document with each unique key, indexed by this unique key and perform a loop over the field of each candidate document cancelling the write if any key is found. IMO this solution is more resource consuming, in change it gets you a list of all keys consumed in written documents.

   db.collection.createIndex( { "unikey": 1}, { unique: true } )
   db.collection.insertMany( {[{"unikey": "$FieldA"},{"unikey": "$FieldB"}]} 
   db.collection.find({"unikey": 1})
Yones
  • 95
  • 7