我的數據庫中有以下結構:{ "_id": { "$oid": "5fc4fc68fcd604bac9f61f71" }, "init": { "fullname": "Besikta Anibula", "parts": [ "Besikta", "Anibula" ], "alt": "Besikta Ani." }, "industry": "E-Commerce"}我試圖只訪問init對象并將結果寫入Go中的結構化變量:var InputData struct { Fullname string `bson:"fullname" json:"fullname"` Parts []string`bson:"parts" json:"parts"` Alt string `bson:"alt" json:"alt"`}collectionRESULTS.FindOne(ctx, options.FindOne().SetProjection(bson.M{"init": 1})).Decode(&InputData)js, _ := json.Marshal(InputData)fmt.Fprint(writer, string(js))但結果是空的:{"fullname":"","parts":null,"alt":""}當不使用如下投影時,它正在工作:var InputData struct { Ident primitive.ObjectID `bson:"_id" json:"id"`}collectionRESULTS.FindOne(ctx, bson.M{}).Decode(&InputData)js, _ := json.Marshal(InputData)fmt.Fprint(writer, string(js))預期結果:{"id":"5fc4fc68fcd604bac9f61f71"}
1 回答

DIEA
TA貢獻1820條經驗 獲得超2個贊
將投影設置為僅檢索結果文檔的屬性,然后嘗試將元化為一個結構值,該值沒有任何匹配字段,因此不會在該結構值中設置任何內容。initinit
必須使用具有字段的值,如以下包裝結構:initResult
type Result struct {
Init InputData `bson:"init"`
}
type InputData struct {
Fullname string `bson:"fullname" json:"fullname"`
Parts []string `bson:"parts" json:"parts"`
Alt string `bson:"alt" json:"alt"`
}
像這樣使用它:
var result Result
err := collectionRESULTS.FindOne(ctx, bson.M{}, options.FindOne().
SetProjection(bson.M{"init": 1})).Decode(&result)
if err != nil {
// handle error
}
- 1 回答
- 0 關注
- 166 瀏覽
添加回答
舉報
0/150
提交
取消