Create a unique field in mongodb

Hi,
I am trying to create a field that is not repeated in any other document, such as _id, but I searched a lot and did not find anything, can you help me?

d,_ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb+srv://user:pass@cluster0.kfhhkba.mongodb.net/?retryWrites=true&w=majority"))

d.Database("database").Collection("collection").UpdateOne(context.TODO(), bson.M{"user":r.FromValue("username")},bson.D{{"$set",bson.D{{"pass",r.FromValue("password ")},{"field_not_repeated",??????}}}})

Hi @mmahdi. Welcome to the community.

You need a unique index on that field, just like _id, which is automatically assigned a unique index during collection creation.

Thanks it works, but there are some problems:
1- When I try to create a document without adding that field, an error appears:

Reason: [08:52:07.642] Error running insert command for 'braq.users' on process 'atlas-bqu6iy-shard-00-01.um0c2p7.mongodb.net:27017' : [08:52:07.642] Error executing WithClientFor() for cp=atlas-bqu6iy-shard-00-01.um0c2p7.mongodb.net:27017 (local=true) connectMode=SingleConnect : [08:52:07.642] Error running command for runCommandWithTimeout(dbName=braq, cmd=[{insert users} {documents [[{_id ObjectID("63f0919e87c53bfc5d5e8293")} {o p}]]} {writeConcern map[w:1]}]) : result="" identityUsed=mms-automation@admin[[MONGODB-CR/SCRAM-SHA-1]][24] : write exception: write errors: [E11000 duplicate key error collection: braq.users index: otpemurl_1 dup key: { otpurl: null }]

I want the unique field mode to be optional.
2- I am using crypto/rand a random string, if crypto/rand generates a similar string it will show an error:

Reason: [08:57:12.827] Error running insert command for 'braq.users' on process 'atlas-bqu6iy-shard-00-01.um0c2p7.mongodb.net:27017' : [08:57:12.827] Error executing WithClientFor() for cp=atlas-bqu6iy-shard-00-01.um0c2p7.mongodb.net:27017 (local=true) connectMode=SingleConnect : [08:57:12.827] Error running command for runCommandWithTimeout(dbName=braq, cmd=[{insert users} {documents [[{_id ObjectID("63f092e087c53bfc5d5e8294")} {otpemurl 1}]]} {writeConcern map[w:1]}]) : result="" identityUsed=mms-automation@admin[[MONGODB-CR/SCRAM-SHA-1]][24] : write exception: write errors: [E11000 duplicate key error collection: braq.users index: otpemurl_1 dup key: { otpemurl: "1" }]

How can I solve these problems?