这几个好理解,

更好的实现,再说。

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")

	docM := map[string]string{
		"name":        "Open Source",
		"description": "Tasks for open-source projects",
	}
	err = c.Insert(docM)
	if err != nil {
		log.Fatal(err)
	}

	docD := bson.D{
		{"name", "Project"},
		{"description", "Project Tasks"},
	}
	err = c.Insert(docD)
	if err != nil {
		log.Fatal(err)
	}

	doc := Category{
		bson.NewObjectId(),
		"Open-Source",
		"Tasks for open-source projects",
		[]Task{
			Task{"Create project in mgo", time.Date(2015, time.August, 10, 0, 0, 0, 0, time.UTC)},
			Task{"Create REST API", time.Date(2015, time.August, 20, 0, 0, 0, 0, time.UTC)},
		},
	}

	err = c.Insert(&doc)
	if err != nil {
		log.Fatal(err)
	}

	var count int
	count, err = c.Count()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("%d records inserted", count)
	}

}

  

12-26 15:14