How to prevent to multiple goroutines/process/thread/applications/... to insert documents in persons collections if already exists person with same name and last name
The only way to prevent duplicate entries esp. in concurrent environment is by using an unique index on {name:1, lastname:1}
. Then in your code, you should be prepared to gracefully handle the exception raised by a potential collision.
Never ever check-before-insert, as in MongoDB you don't have transaction, so it is quite possible that a record was concurrently inserted by an other client after your check and before your insert.
Other peoples might certainly help you more with the correct Go syntax, but something along the lines of the following code (borrowed from here) will allow you to create the required index:
index := mgo.Index{
Key: []string{"name", "lastName"},
Unique: true,
}
err = c.EnsureIndex(index)
Then, every time you insert a document, you need to use the mgo.isDup
function to test if an error was caused by a duplicate key. As an example from a previous answer by @elithrar:
err := users.Insert(user) // where user is type *mgo.Collection
if err != nil {
if mgo.IsDup(err) {
// Is a duplicate key, but we don't know which one
}
// Is another error
}