globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 230 forks source link

Upper case and underline in bson.M Find queries not working properly #156

Closed covrom closed 6 years ago

covrom commented 6 years ago

In dokument like a struct{PostID string `json:"Postid"`} or struct{PostID string `json:"post_id"`}

this samples not working (zero result in non-zero database collection):

err := session.DB(DBName).C("comments").Find(bson.M{"Postid": id).All(comments)

err := session.DB(DBName).C("comments").Find(bson.M{"post_id": id).All(comments)

but this samle is working correct for struct{PostID string} or struct{PostID string `json:"postid"`}:

err := session.DB(DBName).C("comments").Find(bson.M{"postid": id).All(comments)

Why???

szank commented 6 years ago

Hi @covrom, sorry of the late reply.

First, could you please confirm the document format in MongoDB? From what I can see I assume that the document you are trying to retrieve have a field named postid, all lower case.

Mgo is using the BSON serializer : https://godoc.org/github.com/globalsign/mgo/bson. It is a part of the mgo repo. The BSON serializer uses bson tag key, so if you want to use tags to manipulate the field names of the golang structs, you would need to declare them as:

type post struct {
PostID string `bson:"Postid"`
}

Assuming that you used the struct{PostID stringjson:"Postid"} or struct{PostID stringjson:"post_id"} struct to save data to mongo, the BSON serializer have ignored the json tag (it uses the bson tag) and used the lowercased field name as the key in the mongodb document (https://godoc.org/github.com/globalsign/mgo/bson#Marshal)

When calling Find() method on the collection you pass bson.M{"Postid": id}) or bson.M{"post_id": id}) which doesn't return any results, as MongoDB is case sensitive, and the field you are refering to is named postid.

If you want to use custimize the field names in the mongoDB document, you need to use the bson tag.

domodwyer commented 6 years ago

Hi @covrom

I'm going to close this, but feel free to reply - though it's probably best to ask usage questions somewhere like stack overflow.

Dom