相当于select * from table;
package main import ( "fmt" "log" "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Task struct { Description string Due time.Time } type Category struct { Id bson.ObjectId `bson:"_id,omitempty"` Name string Description string Tasks []Task } func main() { mongoDialInfo := &mgo.DialInfo{ Addrs: []string{"localhost"}, Timeout: 5 * time.Second, Database: "taskdb", Username: "root", Password: "123456", } session, err := mgo.DialWithInfo(mongoDialInfo) if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("taskdb").C("categories") iter := c.Find(nil).Iter() result := Category{} for iter.Next(&result) { fmt.Printf("Category: %s, Description: %s\n", result.Name, result.Description) tasks := result.Tasks for _, v := range tasks { fmt.Printf("Task: %s Due: %v\n", v.Description, v.Due) } } if err = iter.Close(); err != nil { log.Fatal(err) } }