亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 MongoDB Projection

使用 MongoDB Projection

Go
忽然笑 2022-08-01 10:03:41
我的數據庫中有以下結構:{  "_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

}


查看完整回答
反對 回復 2022-08-01
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號