gpt4 book ai didi

mongodb - 使用MongoDB投影

转载 作者:行者123 更新时间:2023-12-03 10:09:16 24 4
gpt4 key购买 nike

我的数据库中具有以下结构:

{
"_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"}

最佳答案

您将投影设置为仅检索结果文档的init属性,然后尝试将其解编为没有init值的任何匹配字段的struct值,因此该struct值中将不会设置任何内容。
您必须使用具有init字段的值,例如以下包装Result结构:

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
}

关于mongodb - 使用MongoDB投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65383322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com