mongodb - mongodb ObjectId 的问题
问题描述
我有连接到 mongodb 数据库的 Go 代码。问题是,当我试图从集合中获取记录时,有一个ObjectId
类型为“_id”的字段,但在 mgo 驱动程序ObjectId
中是
type ObjectID [12]byte
但是当我试图获得记录时,Go 说:
reflect.Set:[]uint8 类型的值不可分配给 ObjectID 类型
我试图创建自己的[]uint8
类型,但我不知道如何将[]uint8
(“ObjectId”)转换为string
或通过这些 id 找到一些记录。
// ObjectId type that mongodb wants to see
type ObjectID []uint8
// model
type Edge struct {
ID ObjectID `bson:"_id"`
Name string `bson:"name"`
StartVertex string `bson:"startVertex"`
EndVertex string `bson:"endVertex"`
}
// method for getting record by those id
session, err := mgo.Dial(config.DatabaseURL)
if err != nil {
fmt.Printf("Error is: %s", err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
//edges collection
e := session.DB(config.DatabaseName).C(config.EdgesCollection)
var result models.Edge
err = e.Find(bson.M{"_id": fmt.Sprintln("ObjectId('", id, "')")}).One(&result)
if err != nil {
fmt.Println("Error is: ", err)
}
解决方案
您必须使用“预定义”bson.ObjectId
来模拟 MongoDB 的 ObjectId 的值:
type Edge struct {
ID bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
StartVertex string `bson:"startVertex"`
EndVertex string `bson:"endVertex"`
}
当您通过 ID 查询类型为 MongoDB 的 ObjectId 的对象时,请使用 type 的值bson.ObjectId
。您可以使用以下Collection.FindId()
方法:
var id bson.ObjectId = ...
err = e.FindId(id).One(&result)
在此处查看详细信息:使用 mgo 按 id 查找;和MongoDB 切片查询到 golang
推荐阅读
- log4j - 无法读取 log4j.properties
- ssis - ADO.NET 源无法获取到 mysql 数据库的连接
- javascript - 调用外部文件中声明的函数
- java - 在 Citrus Simulator 中使用 HTTPS
- python - 如何使用 lambda/maps 从 dict 获取列表?
- server - 无法在 debian 上启动 apache2
- python - 与 django 查询集注释中的先前对象的区别
- hadoop-yarn - Flink on yarn 是否使用 yarn-session?
- python - 从python字典制作二维密度图
- vba - 更新链接时自动回复消息框