Home > Backend Development > Golang > Why is my Go code using mgo failing to find a MongoDB document by its _id, even though the _id exists?

Why is my Go code using mgo failing to find a MongoDB document by its _id, even though the _id exists?

Barbara Streisand
Release: 2024-12-30 22:12:15
Original
375 people have browsed it

Why is my Go code using mgo failing to find a MongoDB document by its _id, even though the _id exists?

Find by id with mgo

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
}
Copy after login

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)
Copy after login

Using Collection.Find(): Specify a value with the field name.

err2 := c.Find(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}).
    One(&data)
Copy after login

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template