【发布时间】:2021-09-01 05:05:36
【问题描述】:
我在 mongodb 实例中有一系列集合,我想在其中提取所有集合并解码集合中的所有文档,以便我可以随时改变它们。
我正在使用 go 列出集合名称:
...
collections, err := db.ListCollectionNames(context.TODO(), bson.M{})
if err != nil {
log.Fatalf("Failed to get coll names: %v", err)
}
for _, coll := range collections {
collection := db.Collection(coll)
...
这完美无缺,下一步是为每个集合打开一个游标并在游标上循环,并在每个对象上调用 decode 到其对应的类型。
我已经在一个类型包中定义了所有类型:
type Announcements struct {
Id string `bson:"_id"`
Content string `bson:"content"`
Title string `bson:"title"`
DateModified time.Time `bson:"dateModified,omitempty"`
ModifiedBy string `bson:"modifiedBy,omitempty"`
}
问题是我无法定义用于动态解码的变量。
需要为每个集合重复此代码
var obj Announcements // This would need to be dynamic
for cursor.Next(context.Background()) {
err := cursor.Decode(&obj)
if err != nil {
log.Fatal(err)
}
log.Printf("%#v\n", obj)
}
有没有办法做到这一点而无需重复多次?我意识到动态类型的语言会更好。在我将工作迁移到脚本语言之前想问一下。
我尝试使用反射包和 switch 语句动态实例化变量并使用 interface{} 类型,但这会强制解码使用 bson 类型而不是我定义的结构。
-- 编辑--
我尝试使用映射将集合名称链接到类型,但无济于事。
var Collections = map[string]interface{}{
"announcements": Announcements{},
"badges": Badges{},
"betaUser": BetaUser{},
"bonusLearningItems": BonusLearningItems{},
"books": Books{},
...
}
因此,当我使用 obj var 时,我尝试了如下分配:
var obj types.Collections[coll]
希望如果我被循环到公告集合,这会给我一个公告类型的变量。但是当我调用 decode 它返回 bson 类型。
我需要动态定义obj变量类型。
【问题讨论】: