英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论