MongoDB: ensure uniqueness across multiple documents and fields

70 Views Asked by At

I have a collection of documents storing user information as:

{
    "username": "alex",
    "username_1": "mark",
    "username_2": "james"    
    }
}

I would like to ensure uniqueness both at global (throughout the whole collection) and document level:

  • A defined user identifier must be unique across all selected fields (username, username_1 and username_2) and documents

E.g. An additional "alex" cannot exist as a value for username, username_1 and username_2 for both the document and whole collection.

Thus, the following documents should not be inserted.

# Example 1
{"username": "alex"}
# Example 2
{"username_1": "alex"}

What's the best way to achieve that, within MongoDB?

1

There are 1 best solutions below

0
On

As for the global uniqueness, simply create a text index as:

compound_index = [
      ("username", "text"),
      ("username_1", "text"),
      ("username_2", "text")

]

# Assuming a collection instance has already been created
collection.create_index(compound_index, unique=True)

However, the solution above does not ensure uniqueness at a single document level (e.g. username == username_1, within the same document).