你可以使用golang的mgo MongoDB驱动程序来获取最后插入的ObjectId。

huangapple go评论78阅读模式
英文:

How can I get last inserted ObjectId with golang mgo MongoDb driver

问题

我正在使用Golang的mgo MongoDB驱动程序。

在插入新对象后,我可以获取最后一个ObjectId吗?

还是应该使用bson.NewObjectId手动创建_id

英文:

I am using the mgo MongoDB driver for Golang.

Can I get the last ObjectId after inserting a new object?

Or should I create _id manually with bson.NewObjectId?

答案1

得分: 15

使用mongodb和mgo,通常需要使用bson.NewObjectId自己生成_id值。

《MongoDB手册》中指出:

> 如果文档没有指定_id字段,那么在插入之前,MongoDB会添加_id字段并为文档分配一个唯一的ObjectId。大多数驱动程序会创建一个ObjectId并插入_id字段,但如果驱动程序或应用程序没有这样做,mongod将创建并填充_id

简而言之,自己创建_id是一个好的选择!

英文:

With mongodb, and mgo, you are often expected to generate the _id-value yourself using bson.NewObjectId.

The MongoDB manual states:

> If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

Simply, creating the _id yourself is the way to go!

huangapple
  • 本文由 发表于 2014年3月19日 14:26:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/22497957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定