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

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

使用 MongoDB 解碼將字符串從 MongoDB 轉換為 int

使用 MongoDB 解碼將字符串從 MongoDB 轉換為 int

Go
MMTTMM 2022-05-18 10:21:35
當我嘗試將我的集合中的字符串類型的屬性解碼為我的結構中的 int 類型的屬性時,我在使用 Go 的 mongodb 驅動程序時遇到了一些問題。我有一個集合,該集合的屬性應該是 int 類型,該屬性被編輯單個文檔的人轉換為 string 類型。由于所有文檔都具有該屬性作為 int 除了那個,我收到一個錯誤“無法將字符串解碼為整數類型”。我想出了一種方法來做到這一點,但這不是“應該”做的事情。我在 Go 的 mongodb 驅動程序中修改了 default_value_decoders.go 中的 IntDecodeValue 函數。下面是我添加的。    case bsontype.String:    s, err := vr.ReadString()    if err != nil {        return err    }    i32, err := strconv.Atoi(s)    if err != nil {        return err    }    i64 = int64(i32)我知道當我更新驅動程序時這將被覆蓋,但我一直在努力思考如何處理這種情況。我知道最好的解決方案是不允許直接編輯文檔,但要考慮這種情況。
查看完整描述

2 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您可以通過自定義 BSON 解碼器執行此操作。文檔中的一個示例是https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/bsoncodec?tab=doc#example-Registry-CustomDecoder。對于您的特定用例,以下應該有效:


func intDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) {


// Same logic as DefaultValueDecoders.IntDecodeValue

// In the switch statement for vr.Type, you can add a case for bsontype.String


}

要注冊此解碼器以便在執行 CRUD 操作時使用它,您可以使用SetRegistry客戶端選項:


decoder := bsoncodec.ValueDecoderFunc(intDecodeValue)

registry := bson.NewRegistryBuilder().RegisterDefaultDecoder(reflect.Int, decoder).Build()


clientOpts := options.Client().SetRegistry(registry)

client, err := mongo.Connect(context.TODO(), clientOpts)

請注意,由于 Go 區分不同的整數類型(例如 int8/int16/int32/int64),因此您需要調用RegisterDefaultDecoder為您可能在結構中看到的每種整數類型注冊自定義解碼器,類似于在RegisterDefaultDecoders中的函數default_value_decoders.go。


查看完整回答
反對 回復 2022-05-18
?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

這是在處理字符串和 int 字段的結構中將該字符串字段解碼為 int 的可能解決方案。


我在這個例子中使用了以下結構:


type Obj struct {

    Field1   string `bson:"field1"`

    IntField int    `bson:"intField"`

}

并插入以下文檔(注意第二個文檔的字符串字段為"intField": "2"):


db.s2i.insertOne({"field1": "value", "intField": 3})

db.s2i.insertOne({"field1": "value2", "intField": "2"})

使用聚合框架中的$toInt運算符,如下所示:


pipeline := []bson.M{bson.M{"$match": bson.M{}}, bson.M{"$project": bson.M{"field1": 1, "intField": bson.M{"$toInt": "$intField"}}}}


cur, err := client.Database("stack").Collection("s2i").Aggregate(context.TODO(), pipeline)


for cur.Next(context.TODO()) {

    var res *Obj

    err = cur.Decode(&res)


    fmt.Println(res, err)

    fmt.Println("Value of res.IntField:")

    fmt.Println(res.IntField)

    fmt.Println("Type of res.IntField:")

    fmt.Println(reflect.TypeOf(res.IntField))

}

返回以下文檔,其中“2”解碼為 int:


&{value 3} <nil>

Value of res.IntField:

3

Type of res.IntField:

int

&{value2 2} <nil>

Value of res.IntField:

2

Type of res.IntField:

int


查看完整回答
反對 回復 2022-05-18
  • 2 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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