使用 MongoDB 投影

Using MongoDB Projection

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

{
  "_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 属性,然后您尝试解组为一个结构值,该结构值没有 [=12] 的任何匹配字段=] 值,因此不会在该结构值中设置任何内容。

您必须使用具有 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
}