英文:
Creating ObjectId vs letting DB create it
问题
我正在使用labix mgo模块作为Go语言的Mongo驱动程序。由于Go是并发(和并行)的,所以在应用程序中生成ObjectId是否安全,还是应该只由数据库生成?
如果.Insert()
能够返回Id
,那就非常简单了。但是在我需要它的时候,有两种方法可以实现:
1)在客户端生成ObjectId并使用它
...
user.ID = bson.NewObjectId()
Users.Insert(user)
// 正常使用user.ID
2)让数据库生成Id并检索它
...
Users.Insert(user)
Users.Find(user).One(&user)
// 正常使用user.ID
第二种方法需要进行2次数据库请求和同步插入。
问题是:第一种方法和第二种方法一样安全吗?还是有更好的方法可以使用?
英文:
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:
-
generate ObjectId on client and use it
...
user.ID = bson.NewObjectId()
Users.Insert(user)
// use user.ID normally -
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?
答案1
得分: 3
我会选择第一种方法,因为在这种情况下你不需要检索任何ID。
如果你查看ObjectID的描述,你会发现它由以下部分组成:
- 一个4字节的值,表示自Unix纪元以来的秒数,
- 一个3字节的机器标识符,
- 一个2字节的进程ID,
- 一个3字节的计数器,从一个随机值开始。
正如你所看到的,即使你使用同一台机器上的一个进程(使2和3相同),你仍然能够每秒插入3字节的整数。
所以如果你的写入速度小于(2^8)^3 - 1 = 16777215
每秒,就不会发生冲突。
而每秒插入1600万条记录太不现实了。
英文:
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:
- a 4-byte value representing the seconds since the Unix epoch,
- a 3-byte machine identifier,
- a 2-byte process id, and
- a 3-byte counter, starting with a random value.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论