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。

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
- 2 回答
- 0 關注
- 196 瀏覽
添加回答
舉報