mongodb - 使用 Go 插入和查询 MongoDB 数据

标签 mongodb go

package main

import (
    "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 }

我正在学习 Udemy 的类(class),他们提供了数据结构。对我来说不幸的是,他们提供的示例都是用 PHP 编写的,所以我不得不想办法将所有代码转换为 Go,这很奇怪。

还有第二个注意事项:: 如何将与该结构匹配的数据插入到 mongoDB 集合中? 我试过了,但一直失败。

err = c.Insert(&Customer{"id": 1, "firstName": "Joe", "surname": "Hat", "gender": "M", "address1": "46 Pine Road", "address2": "Apartment 1613", "city": "Scarborough", "state_region": "G.T.A", "county_provine": "Ontario", "postalCode": "M1L 1N1", "country": "Canada", "acct_bal": 8.90, "status": "AAA",})

最佳答案

Export字段名称。

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 编码器 serializes exported fields only .其他序列化器,如 encoding/json 和 encoding/gob 也只适用于导出的字段。

关于mongodb - 使用 Go 插入和查询 MongoDB 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007756/

相关文章:

javascript - 空 XmlHttpRequest.response 但 XHR 包含我的数据

mongodb - 将文档插入 MongoDB 集合时如何处理文档大小超过 16MB 错误

mongodb - org.apache.solr.common.SolrException : TransactionLog doesn't know how to serialize class org. bson.types.ObjectId;尝试实现 ObjectResolver?

go - 在启用安全和隐私的情况下开始对等时出错

go - 使用 go-dockerclient 从自定义注册表下载图像挂起

dependencies - 关于如何避免 Go 中的导入循环有什么好的建议吗?

javascript - 从 html 接收的值更改为在 Node.js 中添加 "\u001c"。如何解决?

mongodb - 教义ODM : Embedding multiple GridFS documents exception

go - 并发写入文件

go - 我不确定为什么索引超出范围错误