Home > Net >  Getting all data from mongodb compound collection with filter in golang
Getting all data from mongodb compound collection with filter in golang

Time:12-10

I try to make get all data with Name field where I specify in API Request Body. I made a filter for .Find() function. But I can't get any result (response body says null, No errors at all). You can see my model file and other parts of the code at bottom.

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

Model File:

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

I tried to filter and get all the data of the user according to the user name. But I think I have a mistake in the filter part or in the overall code because I can't get any data return. I get an empty return.

CodePudding user response:

Your filter would match documents where Patient is an embedded document with a single Name field matching the given value.

To filter by a field of an embedded document, you have to use the dot notation:

filter := bson.M{"Patient.Name": ctx.Query("name")}
  • Related