I think the official doc about cosmos db unique key is clearly stated.
I am trying to create an unique key for an whole collection in Cosmos
DB.
Unique keys must be defined when the container is created, and the unique key is scoped to the partition key.
In the same collection there must be possible to store different
objects without an username.
Sparse unique keys are not supported. If values for some unique paths are missing, they are treated as a special null value, which takes part in the uniqueness constraint.
If you do want to make the username
field unique in the whole collection across the partitions and even null value is permitted, I think you need to check the uniqueness by yourself before inserting documents into cosmos db.I suggest you using pre-triggers to do the check.
Hope it helps you.