首頁  >  文章  >  後端開發  >  使用golang中的過濾器從mongodb複合集合中獲取所有數據

使用golang中的過濾器從mongodb複合集合中獲取所有數據

WBOY
WBOY轉載
2024-02-06 10:36:13608瀏覽

使用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中的過濾器從mongodb複合集合中獲取所有數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除