Skip to content

Update MongoDB documentation #1196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 41 additions & 38 deletions de/05.6.md
Original file line number Diff line number Diff line change
@@ -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

82 changes: 40 additions & 42 deletions en/05.6.md
Original file line number Diff line number Diff line change
@@ -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

73 changes: 39 additions & 34 deletions es/05.6.md
Original file line number Diff line number Diff line change
@@ -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

68 changes: 36 additions & 32 deletions ja/05.6.md
Original file line number Diff line number Diff line change
@@ -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です。



82 changes: 40 additions & 42 deletions th/05.6.md
Original file line number Diff line number Diff line change
@@ -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

49 changes: 24 additions & 25 deletions zh-tw/05.6.md
Original file line number Diff line number Diff line change
@@ -146,25 +146,20 @@ 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 {
@@ -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。



51 changes: 24 additions & 27 deletions zh/05.6.md
Original file line number Diff line number Diff line change
@@ -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。