使用Go插入和查询MongoDB数据

huangapple go评论80阅读模式
英文:

Inserting & Querying MongoDB data with 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"

	// 连接到 MongoDB
	session, err := mgo.Dial(uri)
	if err != nil {
		log.Fatal("无法连接到数据库。", err)
	}
	defer session.Close()

	// 选择集合
	c := session.DB("mydb").C("customers")

	// 查询一条记录
	result := Customer{}
	err = c.Find(bson.M{"status": "B"}).One(&result)
	if err != nil {
		log.Fatal("找不到记录。", err)
	}
	fmt.Println("查询结果:", result)
}

关于如何将符合该结构的数据插入到 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_province: "Ontario",
	postalCode:      "M1L 1N1",
	country:         "Canada",
	acct_bal:        8.90,
	status:          "AAA",
})

希望对你有帮助!如果还有其他问题,请随时提问。

英文:
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)
}

So that's the code,
If I run the MongoShell I get the correct results ::

{
"_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"

}

But the Go file when run gives me this::

One Result:  {ObjectIdHex("528cb19def5c88795f00000a") 0           0 }

I'm following along a course from Udemy and they provide the data structures. Unfortunately for me, the examples they provide are all in PHP so I kind of have to figure out a way to convert all of the code to Go which has been weird.

Also on a second note::
How does one insert a data that matches that struct into a mongoDB collection?
I tried this but it has been a failure.

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",})

答案1

得分: 0

导出字段名。

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也仅适用于导出字段。

英文:

Export the field names.

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"`
}

The BSON encoder serializes exported fields only. Other serializers such as encoding/json and encoding/gob also work with exported fields only.

huangapple
  • 本文由 发表于 2015年1月18日 14:35:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/28007756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定