为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Go 插入和查询 MongoDB 数据

使用 Go 插入和查询 MongoDB 数据

Go
慕盖茨4494581 2021-09-10 21:37:14
package mainimport (    "fmt"    "log"    "gopkg.in/mgo.v2"    "gopkg.in/mgo.v2/bson")type Customer struct {    Id              bson.ObjectId `bson:"_id,omitempty"`    id              int           `bson:"id,"`    firstName       string        `bson:"firstName"`    surname         string        `bson:"surname"`    gender          string        `bson:"gender"`    address1        string        `bson:"address1"`    address2        string        `bson:"address2"`    city            string        `bson:"city"`    state_region    string        `bson:"state_region"`    county_province string        `bson:"county_province"`    postalCode      string        `bson:"postalCode"`    country         string        `bson:"country"`    acct_bal        float64       `bson:"acct_bal"`    status          string        `bson:"status"`}func main() {    uri := "localhost:27017"    // connect to mongodb    session, err := mgo.Dial(uri)    if err != nil {        log.Fatal("Couldn't connect to db.", err)    }    defer session.Close()    // collection    c := session.DB("mydb").C("customers")    // query one    result := Customer{}    err = c.Find(bson.M{"status": "B"}).One(&result)    if err != nil {        log.Fatal("Couldn't find him.", err)    }    fmt.Println("One Result: ", result)}这就是代码,如果我运行 MongoShell,我会得到正确的结果 ::{"_id" : ObjectId("528cb19def5c88795f00000a"),"id" : "00000011","firstName" : "Gerardo","surname" : "Guilfoos","gender" : "M","address1" : "854 Cheerful Breeze Way","address2" : "","city" : "Tavaux","state_region" : "Franche-Comté","county_province" : "Jura","postalCode" : "39501 CEDEX","country" : "FR","acct_balance" : 172.87,"status" : "B"}但是运行时的 Go 文件给了我这个 ::One Result:  {ObjectIdHex("528cb19def5c88795f00000a") 0           0 }还有第二个注意事项:如何将与该结构匹配的数据插入到 mongoDB 集合中?我试过这个,但它一直失败。
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

导出字段名称。


type Customer struct {

    Id              bson.ObjectId `bson:"_id,omitempty"`

    ID              int           `bson:"id"`

    FirstName       string        `bson:"firstName"`

    Surname         string        `bson:"surname"`

    Gender          string        `bson:"gender"`

    Address1        string        `bson:"address1"`

    Address2        string        `bson:"address2"`

    City            string        `bson:"city"`

    State_region    string        `bson:"state_region"`

    County_province string        `bson:"county_province"`

    PostalCode      string        `bson:"postalCode"`

    Country         string        `bson:"country"`

    Acct_bal        float64       `bson:"acct_bal"`

    Status          string        `bson:"status"`

}

BSON 编码器仅序列化导出的字段。其他序列化程序(例如 encoding/json 和 encoding/gob)也仅适用于导出的字段。


查看完整回答
反对 回复 2021-09-10
  • 1 回答
  • 0 关注
  • 355 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号