假设你已经下面的数据结构:
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
}
在Go语言,只有出口领域或方法都可以从外面包。
使用结构标签领域告诉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("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)
}
该方法 Decode
解编找到的数据进入 dest
.