mongodb - 如何使用 mongo-go-driver 从结构转换为文档
问题描述
我正在尝试$push
将 go 结构放入 mongo 数组中。我为本示例简化的 go 文档如下所示:
type Main struct {
ID objectid.ObjectID `bson:"_id"`
Projects []*Project `bson:"proj"`
}
type Project struct {
ID objectid.ObjectID `bson:"_id"`
Name string `bson:"name"`
}
我想要做的是$push
一个新Project
的Main.Projects
阵列。我最终做的事情很痛苦,所以我希望有更好的方法。看这里:
// Create the new project struct:
newProj := &Project{
ID: objectid.New(),
Name: "foo",
}
// Then marshall bson:
bsbuf, err := bsoncodec.Marshal(newProj)
if err != nil {
// ...
}
// Next read the bytes into a document:
bsonDoc, err := bson.ReadDocument(bsbuf)
if err != nil {
// ...
}
// Now create the update document:
upd := bson.NewDocument(
bson.EC.SubDocument("$push", bson.NewDocument(
bson.EC.SubDocument("proj", bsonDoc))))
// And perform update as usual
// ... not shown ...
真的有必要转码到字节缓冲区,然后读入文档吗?我希望有类似的东西:
...
bson.EC.GoStruct("proj", newProj)
...
我确实尝试bson.EC.Interface("proj", newProj)
过,但这只是将空值插入到数组中。我很想知道其他人是如何做这种事情的。
解决方案
你是对的,有一种更简单的方法可以解决这个问题:
newProj := &Project{
ID: objectid.New(),
Name: "foo",
}
upd := bson.M{
"$push": bson.M{"proj": newProj},
}
我在用着github.com/globalsign/mgo/bson
推荐阅读
- java - 使用 docker-java 时出现 java.lang.ClassNotFoundException
- angular - forkJoin 未触发带有片段的 graphql 查询
- php - 如何使用 PHP PicoDb 查询生成器执行包含 DATE_FORMAT 语法的查询?
- jquery - 发现意外数据。\r\n 尝试在 Laravel 中提交日期
- postgresql - 使用变量作为结果数据集
- python - (初学者)Flask 动态路由不起作用
- firebase - 在 null 上调用了 getter 'iterator'。颤振和火力基地
- docker - 如何阻止不同 Docker 网络上的容器之间的通信?
- json - Spring WebClient 不处理 JSON 内容
- latex - 如何在乳胶表格中拆分单元格?