import ( "fmt" "gopkg.in/mgo.v2" ) func main() { // Connect to the default MongoDB database on localhost session, err := mgo.Dial("mongodb://localhost") if err != nil { panic(err) } defer session.Close() // Use the "mydb" database db := session.DB("mydb") // Use the "mycollection" collection collection := db.C("mycollection") // Do something with the collection // ... }
import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Person struct { Name string Age int Email string } func main() { // Connect to the default MongoDB database on localhost session, err := mgo.Dial("mongodb://localhost") if err != nil { panic(err) } defer session.Close() // Use the "mydb" database db := session.DB("mydb") // Use the "people" collection collection := db.C("people") // Insert a new person err = collection.Insert(&Person{Name: "John", Age: 30, Email: "[email protected]"}) if err != nil { panic(err) } // Find all people var people []Person err = collection.Find(bson.M{}).All(&people) if err != nil { panic(err) } // Print all people for _, p := range people { fmt.Println(p.Name, p.Age, p.Email) } }In these examples, we can see that the labix.org.v2.mgo package is used to connect to a MongoDB database, perform database operations such as inserting and querying documents, and work with BSON data. It provides a simple and intuitive API that makes it easy to work with MongoDB databases from Go applications.