Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MGO - empty results returned from Mongo that has results

Tags:

mongodb

go

mgo

I have a GOLANG struct as follows:

type OrgWhoAmI struct {
FriendlyName            string        `json:"friendlyName"`
RedemptionCode          string        `json:"redemptionCode"`
StartUrls               []StartUrl    `json:"startUrls"`
Status                  string        `json:"status"`
Children                []OrgChildren `json:"childrenReemptionCodes"`
}

type StartUrl struct {
DisplayName string `json:"displayName"`
URL         string `json:"url"`
}

type OrgChildren struct {
FriendlyName   string `json:"childFriendlyName"`
RedemptionCode string `json:"childRedemptionCode"`
}

I've created and successfully inserted records into a MongoDB collection (as I can see the results by querying Mongo with the CLI mongo program) - but when I query with MGO as follows, I get nothing:

func main() {
    session, sessionErr := mgo.Dial("localhost")
defer session.Close()

    // Query All
    collection := session.DB("OrgData").C("orgWhoAmI")
var results []OrgWhoAmI
err = collection.Find(bson.M{}).All(&results)
if err != nil {
    panic(err)
}
for _, res := range results {
    fmt.Printf("Result: %s|%s\n", res.FriendlyName, res.RedemptionCode)
}
}

The results printed are:

Result: | Result: | Result: | Result: |

If I ask for the count for records, I get the correct number, but all values for all fields are blank. Not sure what I'm missing here.

like image 343
user2644113 Avatar asked Mar 22 '23 03:03

user2644113


1 Answers

If you aren't creating them in go, it's probably not serializing the key names for you properly. The default for bson is to lowercase the keys, so you need to specify it if you want something else. Also note that you have a typo in OrgWhoAmI for json:"childrenReemptionCodes" (should be Redemption, I'm guessing). You can specify both bson and json separately if you want them to be different.

type OrgWhoAmI struct {
   FriendlyName            string        `bson:"friendlyName" json:"friendlyName"`
   RedemptionCode          string        `bson:"redemptionCode" json:"redemptionCode"`
   StartUrls               []StartUrl    `bson:"startUrls" json:"startUrls"`
   Status                  string        `bson:"status" json:"status"`
   Children                []OrgChildren `bson:"childrenRedemptionCodes" json:"childrenRedemptionCodes"`
}

type StartUrl struct {
   DisplayName string `bson:"displayName" json:"displayName"`
   URL         string `bson:"url" json:"url"`
}

type OrgChildren struct {
   FriendlyName   string `bson:"childFriendlyName" json:"childFriendlyName"`
   RedemptionCode string `bson:"childRedemptionCode" json:"childRedemptionCode"`
}
like image 111
Eve Freeman Avatar answered Apr 02 '23 07:04

Eve Freeman