This is a creation in Article, where the information may have evolved or changed.
github:https://github.com/zhangzhebjut/blog/blob/master/mgo.md
Note : Now MONGODB official has not launched about the official support of the Golang driver, the recommended use is MgO, Detailed Document Description of MgO: Http://godoc.org/labix.org/v2/mgo
Below is an example of using MgO to connect to a MONGODB database in development.
Package Mainimport ("FMT", "Labix.org/v2/mgo" "Labix.org/v2/mgo/bson") type person struct {NAME string PHO NE string}type men struct {Persons []person}const = (URL = "192.168.2.175:27017") func main () {session, Err: = Mgo. Dial (URL)//Connect database if Err! = Nil {panic (ERR)} defer session. Close () session. SetMode (MgO. Monotonic, true) DB: = Session. DB ("MyDB")//Database name collection: = db. C ("person")//If the collection already exists, return directly to the number of elements in the//***** collection ******** countnum, err: = collection. Count () if err! = Nil {panic (err)} FMT. Println ("Things Objects Count:", countnum)//******* insert element ******* temp: = &person{PHONE: "18811577546", NAME: "Zhangzhehero"}//can insert more than one object at a time insert two person object err = collection. Insert (&person{"Ale", "+55 8116 9639"}, temp) if err! = Nil {panic (err)}//***** query Single data ******* Result: = person{} err = collection. Find (Bson. m{"Phone": "456"}). One (&RESULT) FMT.println ("Phone:", result.name, result.) PHONE)//***** Query multiple data ******* var personall men//Storage result iter: = collection. Find (nil). ITER () for ITER. Next (&result) {fmt. Printf ("Result:%v\n", result.name) personall.persons = append (Personall.persons, Result)}//******* Update Data * * * * Err = collection. Update (Bson. m{"name": "CCC"}, Bson. m{"$set": Bson. m{"name": "DDD"}) Err = collection. Update (Bson. m{"name": "DDD"}, Bson. m{"$set": Bson. m{"Phone": "12345678"}) Err = collection. Update (Bson. m{"name": "AAA"}, Bson. m{"Phone": "1245", "Name": "BBB"})//****** Delete data ************ _, Err = collection. RemoveAll (Bson. m{"name": "Ale"})}