diff --git a/de/05.6.md b/de/05.6.md index 64bcc32b2..99eba3138 100644 --- a/de/05.6.md +++ b/de/05.6.md @@ -110,10 +110,10 @@ Let's see how to use the driver that I forked to operate on a database: func main() { var client goredis.Client - + // Set the default port in Redis client.Addr = "127.0.0.1:6379" - + // string manipulation client.Set("a", []byte("hello")) val, _ := client.Get("a") @@ -136,60 +136,63 @@ We can see that it's quite easy to operate redis in Go, and it has high performa ## mongoDB -mongoDB (from "humongous") is an open source document-oriented database system developed and supported by 10gen. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. +mongoDB (from "humongous") is an open source document-oriented database system developed and supported by MongoDB, Inc. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. ![](images/5.6.mongodb.png?raw=true) -Figure 5.1 MongoDB compared to Mysql - -The best driver for mongoDB is called `mgo`, and it is possible that it will be included in the standard library in the future. +Figure 5.1 MongoDB compared to MySQL -Here is the example: +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver) is the official MongoDB Go Driver. +Here is an example: ```Go +package main - package main +import ( + "context" + "log" - import ( - "fmt" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" - "log" - ) + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +type Person struct { + Name string + Phone string +} + +func main() { + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") - type Person struct { - Name string - Phone string + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Fatal(err) } - func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") - if err != nil { - panic(err) - } - defer session.Close() + defer client.Disconnect(context.TODO()) - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + coll := client.Database("test").Collection("test") - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) - if err != nil { - log.Fatal(err) - } + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) + if err != nil { + log.Fatalf("InsertOne failed: %v", err) + } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) - } + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } - fmt.Println("Phone:", result.Phone) + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } + log.Printf("Found person: %v", person) +} ``` -We can see that there are no big differences when it comes to operating on mgo or beedb databases; they are both based on structs. This is the Go way of doing things. +We can see that there are no big differences when it comes to operating on MongoDB Go Driver or beedb databases; they are both based on structs. This is the Go way of doing things. ## Links diff --git a/en/05.6.md b/en/05.6.md index 59d14bad7..9fc9a2593 100644 --- a/en/05.6.md +++ b/en/05.6.md @@ -108,10 +108,10 @@ Let's see how to use the driver that I forked to operate on a database: func main() { var client goredis.Client - + // Set the default port in Redis client.Addr = "127.0.0.1:6379" - + // string manipulation client.Set("a", []byte("hello")) val, _ := client.Get("a") @@ -134,66 +134,64 @@ We can see that it is quite easy to operate redis in Go, and it has high perform ## mongoDB -mongoDB (from "humongous") is an open source document-oriented database system developed and supported by 10gen. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. +mongoDB (from "humongous") is an open source document-oriented database system developed and supported by MongoDB, Inc. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. ![](images/5.6.mongodb.png?raw=true) -Figure 5.1 MongoDB compared to Mysql - -The best driver for mongoDB is called `mgo`, and it is possible that it will be included in the standard library in the future. +Figure 5.1 MongoDB compared to MySQL -Install mgo: +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver) is the official MongoDB Go Driver. +Here is an example: ```Go - go get gopkg.in/mgo.v2 -``` +package main -Here is the example: -```Go +import ( + "context" + "log" - package main + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) - import ( - "fmt" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" - "log" - ) +type Person struct { + Name string + Phone string +} + +func main() { + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") - type Person struct { - Name string - Phone string + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Fatal(err) } - func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") - if err != nil { - panic(err) - } - defer session.Close() + defer client.Disconnect(context.TODO()) - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + coll := client.Database("test").Collection("test") - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) - if err != nil { - log.Fatal(err) - } + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) + if err != nil { + log.Fatalf("InsertOne failed: %v", err) + } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) - } + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } - fmt.Println("Phone:", result.Phone) + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } + log.Printf("Found person: %v", person) +} ``` -We can see that there are no big differences when it comes to operating on mgo or beedb databases; they are both based on structs. This is the Go way of doing things. +We can see that there are no big differences when it comes to operating on MongoDB Go Driver or beedb databases; they are both based on structs. This is the Go way of doing things. ## Links diff --git a/es/05.6.md b/es/05.6.md index fdf6b552b..61f68da14 100644 --- a/es/05.6.md +++ b/es/05.6.md @@ -135,59 +135,64 @@ Como podemos ver es muy sencillo operar redis en Go, y como tiene un alto rendim ## mongoDB -mongoDB (de "humongous" (enorme)) es una bases de datos orientada a documentos de código abierto desarrollado y mantenida por 10gen. Hace parte de la familia de bases de datos NoSQL. En lugar de almacenar la información en tablas como es hecho en bases de datos relacionales 'clasicas', MongoDB guarda la información en estructurada en documentos al estilo JSON con esquemas dinámicos (MongoDB llama el formato BSON) haciendo que la integración de los datos en cierto tipo de aplicaciones sea mas fácil y rápido. +mongoDB (de "humongous" (enorme)) es una bases de datos orientada a documentos de código abierto desarrollado y mantenida por MongoDB, Inc. Hace parte de la familia de bases de datos NoSQL. En lugar de almacenar la información en tablas como es hecho en bases de datos relacionales 'clasicas', MongoDB guarda la información en estructurada en documentos al estilo JSON con esquemas dinámicos (MongoDB llama el formato BSON) haciendo que la integración de los datos en cierto tipo de aplicaciones sea mas fácil y rápido. ![](images/5.6.mongodb.png?raw=true) -Figura 5.1 MongoDB comparada con Mysql +Figura 5.1 MongoDB comparada con MySQL -El mejor manejador para mongoDB es llamado `mgo`, y es posible que se incluya en la librería estándar en el futuro. +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver) es la oficial MongoDB Go Driver. Aquí está un ejemplo ```Go +package main - package main +import ( + "context" + "log" - import ( - "fmt" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" - "log" - ) + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) - type Person struct { - Name string - Phone string +type Person struct { + Name string + Phone string +} + +func main() { + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") + + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Fatal(err) } - func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") - if err != nil { - panic(err) - } - defer session.Close() + defer client.Disconnect(context.TODO()) - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + coll := client.Database("test").Collection("test") - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) - if err != nil { - log.Fatal(err) - } + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) + if err != nil { + log.Fatalf("InsertOne failed: %v", err) + } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) - } + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } - fmt.Println("Phone:", result.Phone) + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } + log.Printf("Found person: %v", person) +} ``` -Como podemos ver no hay muchas diferencias en lo que respecta a operar con mgo o bases de datos beedb; ambas son basadas en estructuras. Esta es la manera en que Go hace las cosas. + +Como podemos ver no hay muchas diferencias en lo que respecta a operar con MongoDB Go Driver o bases de datos beedb; ambas son basadas en estructuras. Esta es la manera en que Go hace las cosas. ## Enlaces diff --git a/ja/05.6.md b/ja/05.6.md index 7ba587c67..fedc656ef 100644 --- a/ja/05.6.md +++ b/ja/05.6.md @@ -142,55 +142,59 @@ MongoDBは高性能でオープンソース、モードレスなドキュメン 図5.1 MongoDBとMysqlの操作の対応図 -現在GoでサポートされているmongoDBのもっとも良いドライバは[mgo](http://labix.org/mgo)です。このドライバは現在もっともオフィシャルのpkgになりそうなものです。 +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver)はMongoDB公式のGo用のドライバです。 次にどのようにしてGoからmongoDBを操作するのかご説明します: ```Go +package main - package main +import ( + "context" + "log" - import ( - "fmt" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" - "log" - ) + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) - type Person struct { - Name string - Phone string +type Person struct { + Name string + Phone string +} + +func main() { + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") + + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Fatal(err) } - func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") - if err != nil { - panic(err) - } - defer session.Close() + defer client.Disconnect(context.TODO()) - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + coll := client.Database("test").Collection("test") - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) - if err != nil { - log.Fatal(err) - } + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) + if err != nil { + log.Fatalf("InsertOne failed: %v", err) + } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) - } + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } - fmt.Println("Phone:", result.Phone) + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } + log.Printf("Found person: %v", person) +} ``` -mgoの操作方法とbeedbの操作方法はほとんど似ていることがわかります。どちらもstructに基づいて操作する方法です。これこそがGo Styleです。 +MongoDBの公式ドライバの操作方法とbeedbの操作方法はほとんど似ていることがわかります。どちらもstructに基づいて操作する方法です。これこそがGo Styleです。 diff --git a/th/05.6.md b/th/05.6.md index 327c24822..c2fe0e192 100644 --- a/th/05.6.md +++ b/th/05.6.md @@ -108,10 +108,10 @@ Let's see how to use the driver that I forked to operate on a database: func main() { var client goredis.Client - + // Set the default port in Redis client.Addr = "127.0.0.1:6379" - + // string manipulation client.Set("a", []byte("hello")) val, _ := client.Get("a") @@ -134,66 +134,64 @@ We can see that it is quite easy to operate redis in Go, and it has high perform ## mongoDB -mongoDB (from "humongous") is an open source document-oriented database system developed and supported by 10gen. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. +mongoDB (from "humongous") is an open source document-oriented database system developed and supported by MongoDB, Inc. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. ![](images/5.6.mongodb.png?raw=true) -Figure 5.1 MongoDB compared to Mysql - -The best driver for mongoDB is called `mgo`, and it is possible that it will be included in the standard library in the future. +Figure 5.1 MongoDB compared to MySQL -Install mgo: +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver) is the official MongoDB Go Driver. +Here is an example: ```Go - go get gopkg.in/mgo.v2 -``` +package main -Here is the example: -```Go +import ( + "context" + "log" - package main + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) - import ( - "fmt" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" - "log" - ) +type Person struct { + Name string + Phone string +} + +func main() { + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") - type Person struct { - Name string - Phone string + client, err := mongo.Connect(context.TODO(), clientOptions) + if err != nil { + log.Fatal(err) } - func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") - if err != nil { - panic(err) - } - defer session.Close() + defer client.Disconnect(context.TODO()) - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + coll := client.Database("test").Collection("test") - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) - if err != nil { - log.Fatal(err) - } + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) + if err != nil { + log.Fatalf("InsertOne failed: %v", err) + } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) - } + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } - fmt.Println("Phone:", result.Phone) + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } + log.Printf("Found person: %v", person) +} ``` -We can see that there are no big differences when it comes to operating on mgo or beedb databases; they are both based on structs. This is the Go way of doing things. +We can see that there are no big differences when it comes to operating on MongoDB Go Driver or beedb databases; they are both based on structs. This is the Go way of doing things. ## Links diff --git a/zh-tw/05.6.md b/zh-tw/05.6.md index dc6fd6d3d..ff0f0d42a 100644 --- a/zh-tw/05.6.md +++ b/zh-tw/05.6.md @@ -146,13 +146,7 @@ MongoDB 是一個高效能、開源的文件型資料庫,是一個介於關聯 圖 5.1 MongoDB 和 Mysql 的操作對比圖 -目前 Go 支援 mongoDB 最好的驅動就是[mgo](http://labix.org/mgo),這個驅動目前最有可能成為官方的 pkg。 - -安裝 mgo: - -```Go -go get gopkg.in/mgo.v2 -``` +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver)是 MongoDB 官方的 Go 驅動。 下面我將示範如何透過 Go 來操作 mongoDB: @@ -160,11 +154,12 @@ go get gopkg.in/mgo.v2 package main import ( - "fmt" + "context" "log" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" ) type Person struct { @@ -173,33 +168,37 @@ type Person struct { } func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") + + client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { - panic(err) + log.Fatal(err) } - defer session.Close() - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + defer client.Disconnect(context.TODO()) - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) + coll := client.Database("test").Collection("test") + + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) if err != nil { - log.Fatal(err) + log.Fatalf("InsertOne failed: %v", err) } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) + } + + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) } - fmt.Println("Phone:", result.Phone) + log.Printf("Found person: %v", person) } ``` -我們可以看出來 mgo 的操作方式和 beedb 的操作方式幾乎類似,都是基於 struct 的操作方式,這個就是 Go Style。 +我們可以看出來 MongoDB 官方 Go 驅動的操作方式和 beedb 的操作方式幾乎類似,都是基於 struct 的操作方式,這個就是 Go Style。 diff --git a/zh/05.6.md b/zh/05.6.md index 5709f36f1..8343318c3 100644 --- a/zh/05.6.md +++ b/zh/05.6.md @@ -145,25 +145,19 @@ MongoDB是一个高性能,开源,无模式的文档型数据库,是一个 图5.1 MongoDB和Mysql的操作对比图 -目前Go支持mongoDB最好的驱动就是[mgo](http://labix.org/mgo),这个驱动目前最有可能成为官方的pkg。 - -安装mgo: - -```Go -go get gopkg.in/mgo.v2 -``` +[mongodb/mongo-go-driver](https://github.com/mongodb/mongo-go-driver)是MongoDB官方的Go驱动。 下面我将演示如何通过Go来操作mongoDB: ```Go - package main import ( - "fmt" + "context" "log" - "gopkg.in/mgo.v2" - "gopkg.in/mgo.v2/bson" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" ) type Person struct { @@ -172,33 +166,36 @@ type Person struct { } func main() { - session, err := mgo.Dial("server1.example.com,server2.example.com") + clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") + + client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { - panic(err) + log.Fatal(err) } - defer session.Close() - // Optional. Switch the session to a monotonic behavior. - session.SetMode(mgo.Monotonic, true) + defer client.Disconnect(context.TODO()) - c := session.DB("test").C("people") - err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, - &Person{"Cla", "+55 53 8402 8510"}) + coll := client.Database("test").Collection("test") + + _, err = coll.InsertOne(context.TODO(), Person{"Alice", "123"}) if err != nil { - log.Fatal(err) + log.Fatalf("InsertOne failed: %v", err) } - result := Person{} - err = c.Find(bson.M{"name": "Ale"}).One(&result) - if err != nil { - log.Fatal(err) + result := coll.FindOne(context.TODO(), bson.D{{"name", "Alice"}}) + if err := result.Err(); err != nil { + log.Fatalf("FindOne failed: %v", err) } - fmt.Println("Phone:", result.Phone) -} + var person Person + if err = result.Decode(&person); err != nil { + log.Fatalf("Decode failed: %v", err) + } + log.Printf("Found person: %v", person) +} ``` -我们可以看出来mgo的操作方式和beedb的操作方式几乎类似,都是基于struct的操作方式,这个就是Go Style。 +我们可以看出来MongoDB官方Go驱动的操作方式和beedb的操作方式几乎类似,都是基于struct的操作方式,这个就是Go Style。