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

标签 mongodb go collections mongo-go

我尝试使用我在 API 请求正文中指定的名称字段获取所有数据。我为 .Find() 函数做了一个过滤器。但是我得不到任何结果(响应主体说 null,完全没有错误)。您可以在底部看到我的模型文件和代码的其他部分。

Controller :

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")}

关于mongodb - 使用golang中的过滤器从mongodb复合集合中获取所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74752419/

相关文章:

c# - 只读列表<字典<>>

scala - 如何将选项添加到列表

MongoDB YAML "Unrecognized option: security"

arrays - 如何在 MongoDB 中同时查询两个数组?

javascript - MongoDB 对具有相似子文档的文档进行建模

elasticsearch - 在 google go 中使用 olivere/elastic 通过 ElasticSearch 中的查询更新记录

java - 如何选择不符合Mongo中某些字段的文档使用Java?

json - 如何使用具有正确 MIME 类型的 httprouter 提供静态文件?

google-app-engine - 使用 Google App Engine SDK 在 Go 中进行简单应用

java - Collections.singleton() 返回 Set 而不是 Collection 有什么好处?