Right way to pull data from mongodb in golang

huangapple go评论105阅读模式
英文:

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:&quot;_id&quot;`
	Title       string             `bson:&quot;product&quot;`
	Description string             `bson:&quot;description&quot;`

	count int64 // &lt;- this is not exported, so data won&#39;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(&quot;mongodb://localhost:27017/&quot;))
    if err != nil {
	    log.Fatalf(&quot;can&#39;t connect to database: %v\n&quot;, err)
    }
    
    objID, _ := primitive.ObjectIDFromHex(&quot;619dd79acad38082f9ce16af&quot;)
    
    db := client.Database(&quot;db&quot;)
    col := db.Collection(&quot;products&quot;)
    
    filter := bson.D{
        {&quot;_id&quot;, objID},
    }
    
    dest := &amp;Project{}
    
    err := col.FindOne(ctx, filter).Decode(dest)
    if err != nil {
        log.Fatalln(err)
    }

The method Decode Unmarshals found data into dest.

huangapple
  • 本文由 发表于 2021年11月24日 06:29:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/70088621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定