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?
As for the global uniqueness, simply create a text index as:
However, the solution above does not ensure uniqueness at a single document level (e.g. username == username_1, within the same document).