Question: I would like to find a data by _id. I know that this data exists and that this _id exist (I've tested it with pymongo). However, the code below doesn't find it:
type id_cookie struct { IdCookie int } func get_id_mongo() int { session, err := mgo.Dial("127.0.0.1") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) c := session.DB("id_bag").C("id_cookie") data := id_cookie{} err2 := c.FindId(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}).One(&data) if (err2 != nil){ Info.Println("error") Info.Println(err2) } Info.Println(data) return data.IdCookie }
Answer: There are two ways to find by id using Collection.FindId() or Collection.Find().
Using Collection.FindId(): Pass only the id value.
err2 := c.FindId(bson.ObjectIdHex("58593d1d6aace357b32bb3a1")).One(&data)
Using Collection.Find(): Specify a value with the field name.
err2 := c.Find(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}). One(&data)
If you still get 0 as the value of id_cookie.IdCookie, it means the field in the document holding this id has a different name. Use struct tags to map it accordingly.
type id_cookie struct { IdCookie int `bson:"myid"` }
To avoid performance issues, connect to the MongoDB server once and reuse the session. For more details, refer to the following thread: [mgo - query performance seems consistently slow (500-650ms)](https://groups.google.com/forum/#!topic/golang-nuts/8_EH7KO_S4Y).
The above is the detailed content of Why is my Go code using mgo failing to find a MongoDB document by its _id, even though the _id exists?. For more information, please follow other related articles on the PHP Chinese website!