I am using labix mgo module as a Go Mongo driver. Since Go is concurrent (and parallel), is it safe to generate ObjectId in application or should only database do that?
It would be really straightforward if .Insert()
could return Id
. But this way when I need it, there are two approaches how I do that:
1) generate ObjectId on client and use it
...
user.ID = bson.NewObjectId()
Users.Insert(user)
// use user.ID normally
2) let the database generate the Id and retrieve it
...
Users.Insert(user)
Users.Find(user).One(&user)
// user user.ID normally
The second approach takes 2 database requests and the synchronous insert.
Question is: Is first approach safe as second is? Or is there something better I should be working with?
I would go with the first approach, as you will not need to retrieve any ID in this case.
If you will look at the description of ObjectID, you will see that it consists of:
As you see, even if you use the same machine running on one process (making 2 and 3 the same), you still are able to insert 3 bytes integer per second.
So if your writing speed is less than (2^8)^3 - 1 = 16777215
per second, the collision will not happen.
And having 16 million inserts per second is too unrealistic.