package main import ( "fmt" "log" "labix.org/v2/mgo" ) func main() { session, err := mgo.Dial("mongodb://localhost") if err != nil { log.Fatal(err) } defer session.Close() // Select database and collection db := session.DB("mydb") col := db.C("mycollection") // Insert a document err = col.Insert(&Person{Name: "John", Age: 35}) if err != nil { log.Fatal(err) } // Query for a document var result Person err = col.Find(bson.M{"name": "John"}).One(&result) if err != nil { log.Fatal(err) } fmt.Println(result.Name, result.Age) } type Person struct { Name string Age int }
package main import ( "log" "labix.org/v2/mgo" ) func main() { session, err := mgo.Dial("mongodb://localhost") if err != nil { log.Fatal(err) } defer session.Close() // Enable session management session.SetMode(mgo.Monotonic, true) // Select database and collection db := session.DB("mydb") col := db.C("mycollection") // Start a session s := session.Copy() defer s.Close() // Run operations inside the session err = s.DB("mydb").C("mycollection").Insert(&Person{Name: "Jane", Age: 25}) if err != nil { log.Fatal(err) } err = s.DB("mydb").C("mycollection").Remove(bson.M{"name": "John"}) if err != nil { log.Fatal(err) } } type Person struct { Name string Age int }Example 2 demonstrates the use of sessions. It first enables session management by calling `session.SetMode(mgo.Monotonic, true)`. It then starts a new session using `session.Copy()`, and runs operations inside the session. Finally, it closes the session with `defer s.Close()`. Overall, go labix.org.v2.mgo Session DB is a powerful and feature-rich package library for working with MongoDB databases in Go.