英文:
Right way to pull data from mongodb in golang
问题
我有一个以以下格式存储在MongoDB中的文档:
{
field1: string,
field2: float64,
field3: {...float64}
}
最终,我希望始终获取field1和field2,并从field3对象中进行选择。
为了实现这一点,我将数据解码为以下结构体:
type MongoScore struct {
field1 string `json:"field1"`
field2 float64 `json:"field2"`
field3 map[string]float64 `json:"field3"`
}
我想知道的部分是是否有更高效的方法来提取具有不同类型的数据。
英文:
I have a document in mongodb in this format,
{
field1: string,
field2: float64,
field3: {...float64}
}
Ultimately I would like to always get field1 & field2 and pick/choose from the field3 object.
To do it, I decode the data into a struct like this,
type MongoScore struct {
field1 string `json:"field1"`
field2 float64 `json:"field2"`
field3 map[string]float64 `json:"field3"`
}
The part I am wondering is whether there is a more efficient approach to pull this data with different types.
答案1
得分: 1
假设你有以下的数据结构:
type Product struct {
ID primitive.ObjectID `bson:"_id"`
Title string `bson:"product"`
Description string `bson:"description"`
count int64 // <- 这个字段没有导出,所以数据不会被填充
}
在 Golang 中,只有导出的字段或方法才能从包外部访问。
使用结构体字段标签告诉 MongoDB 将数据直接加载到匹配的字段中。在这里,MongoDB 使用 bson
标签与集合中的字段进行匹配。
func main() {
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017/"))
if err != nil {
log.Fatalf("无法连接到数据库:%v\n", err)
}
objID, _ := primitive.ObjectIDFromHex("619dd79acad38082f9ce16af")
db := client.Database("db")
col := db.Collection("products")
filter := bson.D{
{"_id", objID},
}
dest := &Product{}
err := col.FindOne(ctx, filter).Decode(dest)
if err != nil {
log.Fatalln(err)
}
}
Decode
方法将找到的数据解组为 dest
。
英文:
Assuming you have the following data struct:
type Product struct {
ID primitive.ObjectID `bson:"_id"`
Title string `bson:"product"`
Description string `bson:"description"`
count int64 // <- this is not exported, so data won't be filled
}
In Golang, Only exported fields or methods are accessible from outside it's package.
Use struct field tags to tell Mongodb load the data from collection straight to the matched fields. Here mongodb matches bson
tag with fields in collection.
func main() {
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017/"))
if err != nil {
log.Fatalf("can't connect to database: %v\n", err)
}
objID, _ := primitive.ObjectIDFromHex("619dd79acad38082f9ce16af")
db := client.Database("db")
col := db.Collection("products")
filter := bson.D{
{"_id", objID},
}
dest := &Project{}
err := col.FindOne(ctx, filter).Decode(dest)
if err != nil {
log.Fatalln(err)
}
The method Decode
Unmarshals found data into dest
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论