卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

使用golang中的过滤器从mongodb复合集合中获取所有数据

使用golang中的过滤器从mongodb复合集合中获取所有数据

问题内容

我尝试使用我在 api 请求正文中指定的名称字段获取所有数据。我为 .find() 函数创建了一个过滤器。但我无法得到任何结果(响应正文显示 null,根本没有错误)。您可以在底部看到我的模型文件和代码的其他部分。

控制器:

func get_formbypatientfullname(ctx *gin.context) {
   col := mongodb.client.database(config.database_name).collection("consentforms")
   filter := bson.m{"patient": bson.m{"name": ctx.query("name")}}

   cursor, err := col.find(_context.todo(), filter)
   if err != nil {
      log.fatal(err)
   }

   var results []general_models.consentform
   if err = cursor.all(_context.todo(), &results); err != nil {
      log.fatal(err)
   }
   for _, result := range results {
      res, _ := json.marshal(result)
      fmt.println(string(res))
   }
   ctx.indentedjson(http.statusok, gin.h{"data": results})
}

模型文件:

type ConsentForm struct {
   ID                 primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
   FormFileURL        string             `json:"FormFileURL" bson:"FormFileURL"`
   ProcessName        string             `json:"ProcessName" bson:"ProcessName"`
   DateOfNotification string             `json:"DateOfNotification" bson:"DateOfNotification"`
   WitnessName        string             `json:"WitnessName" bson:"WitnessName"`
   WitnessSurname     string             `json:"WitnessSurname" bson:"WitnessSurname"`
   ResponsibleDoctor  string             `json:"ResponsibleDoctor" bson:"ResponsibleDoctor"`
   Patient            IPatient           `json:"Patient" bson:"Patient"`
   QuestionOptions    IQuestionOptions   `json:"QuestionOptions" bson:"QuestionOptions"`
   AdditionalDetails  string             `json:"AdditionalDetails" bson:"AdditionalDetails"`
}

type IPatient struct {
   // ID                primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
   Name              string `json:"Name" bson:"Name"`
   Surname           string `json:"Surname" bson:"Surname"`
   Birthdate         string `json:"Birthdate" bson:"Birthdate"`
   TCKN              string `json:"TCKN" bson:"TCKN"`
   FacePhotoURL      string `json:"FacePhotoURL" bson:"FacePhotoURL"`
   SignatureImageURL string `json:"SignatureImageURL" bson:"SignatureImageURL"`
}

我尝试根据用户名过滤并获取用户的所有数据。但我认为我在过滤器部分或整个代码中存在错误,因为我无法获得任何数据返回。我得到的回报是空的。


正确答案


您的过滤器将匹配其中 patient 是嵌入文档且具有与给定值匹配的单个 name 字段的文档。

要按嵌入文档的字段进行过滤,您必须使用点符号:

filter := bson.M{"Patient.Name": ctx.Query("name")}
卓越飞翔博客
上一篇: Golang 指针混淆,如何从函数获取指针,然后传递给修改函数
下一篇: 我的神经网络(从头开始)训练,让它离目标更远
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏