Reputation: 2777
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.
Upvotes: 1
Views: 848
Reputation: 627
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
.
Upvotes: 1