代码之家  ›  专栏  ›  技术社区  ›  Velidan

如何在MGO mongo db driver for golang中获取我的文档的ObjectId(\u id)

  •  2
  • Velidan  · 技术社区  · 7 年前

    我正在与MGO合作(因为我没有找到比它更好的东西)。 I'have played with it and have have some result but I don know how to get the \u id(internal Mongo ObjectId)of document received?I'have played and have have some result,but I don know to get the \u id(internal Mongo ObjectId)of document received?

    对于ex:

    type FunnyNumber struct {
        Value int
        _id string
    }
    
    session, err := mgo.Dial("127.0.0.1:27017")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    
    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)
    
    c := session.DB("m101").C("funnynumbers")
    
    funnynumber := FunnyNumber{}
    err = c.Find(bson.M{}).One(&funnynumber)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Id one:", funnynumber._id)  // Nothing here? WHy? How to get it.
    fmt.Println("Value one:", funnynumber.Value)  // 62. It's OK!
    

    谁能帮帮我吗?Ot我在哪里可以读到一些关于它的信息?我在MGO文件里没找到任何东西

    我的文档架构为:

    { "_id" : ObjectId("50778ce69331a280cf4bcf90"), "value" : 62 }
    

    谢谢

    1 回复  |  直到 7 年前
        1
  •  5
  •   Himanshu    7 年前
    1. 改变 _id 变量转换为大写(ID),使其可导出。
    2. 使用 bson.ObjectID 作为其类型。
    3. 为结构添加标记 FunnyNumber Id变量。 领域

    要获得对象Id值,应该做以上三件事。

    import "labix.org/v2/mgo/bson"
    
    type FunnyNumber struct {
        Value int `json:"value"`
        Id bson.ObjectId `bson:"_id,omitempty"`` // only uppercase variables can be exported
    }
    

    看看包装 BSON 了解在使用mongodb时如何使用bson标记