Background of 0.

Mgo is a client program and driver that connects to MongoDB database. We used it to connect to MongoDB.

mgo

1. Introduction

Mgo: (pronounced mango) is a MongoDB driver for the Go language that implements a rich and well-tested feature selection under a very simple API that follows standard Go idioms.

Outstanding Features:

  • Cluster discovery and Communication: MGO provides automated cluster topology discovery and maintenance.
  • Failover management: MGO will automatically failover when the primary server changes.
  • Synchronization and concurrency: Concurrent operations on the same socket do not wait for a round trip from the previous operation before delivery. When you receive the first document from the network, you can also start processing the document immediately and continue receiving it in the background.
  • Result prefetch: When a determined percentage of the current batch is processed, the next batch of results is automatically requested.
  • Flexible serialization: MGO supports flexible marshalling and unmarshalling of documents via gobson
  • Authentication support for pooling integration: MGO provides authentication support with powerful connection pooling integration.
  • GridFS support: MGO can be used to send and receive files to MongoDB.
  • Full testing: Automated testing also covers severe cases, such as primary failover.

2. Operation example

2.1 installation

go get gopkg.in/mgo.v2
Copy the code

2.2 the import

import (
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
)
Copy the code

2.3 Establishing connections

The connection is established using mgo.dial (), which returns a session object.

session, err := mgo.Dial("server1.example.com,server2.example.com") if err ! = nil { panic(err) } defer session.Close()Copy the code

Get a collection

 c := session.DB("test").C("people")
Copy the code

Insert data

Call the Insert method.

err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"}) if err ! = nil { log.Fatal(err) }Copy the code

The query

Call the Find method.

result := Person{} err = c.Find(bson.M{"name": "Ale"}).One(&result) if err ! = nil { log.Fatal(err) } fmt.Println("Phone:", result.Phone)Copy the code

3. Read more

  • API docs for mgo
  • API docs for mgo/bson
  • API docs for mgo/txn

4. Reference

labix.org/mgo