Search code examples
databaseuniquearangodbaql

How to ensure that a field in a document is unique in ArangoDB?


I had created a collection in ArangoDB and need to say that one field is unique. For example I need to say that in 'user_table' 'email' is unique. How to do that?


Solution

  • To ensure uniqueness of a certain attribute in a collection, you can use the ensureUniqueConstraint function for the collection:

    db['user_table'].ensureUniqueConstraint("email");
    

    This will create a non-sparse unique index on attribute email.

    If email is an optional attribute, you may want to go with:

    db['user_table'].ensureUniqueConstraint("email", { sparse: true });
    

    As @CoDEmanX mentioned, it's also possible to use the more general ensureIndex method and specify index type and uniqueness as parameters:

    db['user_table'].ensureIndex({ fields: ["email"], type: "hash", unique: true, sparse: true });