go - 如何使用 golang mgo MongoDb 驱动程序获取最后插入的 ObjectId

标签 go mgo

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

插入新对象后能否获取到最后的ObjectId

或者我应该用 bson.NewObjectId 手动创建 _id 吗?

最佳答案

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

MongoDB manual状态:

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.

简单地说,自己创建 _id 是可行的方法!

关于go - 如何使用 golang mgo MongoDb 驱动程序获取最后插入的 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497957/

相关文章:

windows - 在 Go 中执行一个 vbscript

mysql - 在 Go REST-API 中传输 MySQL JSON 数据类型

mongodb - 具有嵌套嵌入文档和 $project 的 Mongo 聚合管道 $lookup

mongodb - 当键包含大写字母时无法使用 mgo 检索值

select - 查询文档并选择子文档

go - 对于给定的接口(interface),我有三个实现。三个实现如何共享相同的方法?

http - 如何在golang中使用multipart

go - html/模板 : pattern matches no files even with absolute path

MongoDB in Go (golang) with mgo : How do I update a record, 找出更新是否成功并在单个原子操作中获取数据?

mongodb - 如何使用 mgo 在单个集合中处理多种类型