Beispiel #1
0
func main() {
	var (
		mongoSession *mgo.Session
		database     *mgo.Database
		collection   *mgo.Collection
		changeInfo   *mgo.ChangeInfo
		err          error
	)

	if mongoSession, err = mgo.Dial("localhost"); err != nil {
		panic(err)
	}

	database = mongoSession.DB("mgo_examples_03")
	collection = database.C("todos")

	// START OMIT
	var todo = Todo{
		Id:      bson.NewObjectId(),
		Task:    "Demo mgo",
		Created: time.Now(),
	}

	// This is a shortcut to collection.Upsert(bson.M{"_id": todo.id}, &todo)
	if changeInfo, err = collection.UpsertId(todo.Id, &todo); err != nil {
		panic(err)
	}
	// END OMIT

	fmt.Printf("Todo: %# v", pretty.Formatter(todo))
	fmt.Printf("Change Info: %# v", pretty.Formatter(changeInfo))

}
Beispiel #2
0
func main() {
	var (
		mongoSession *mgo.Session
		database     *mgo.Database
		collection   *mgo.Collection
		err          error
	)

	if mongoSession, err = mgo.Dial("localhost"); err != nil {
		panic(err)
	}

	database = mongoSession.DB("mgo_examples_05")
	collection = database.C("todos")

	var todos []Todo
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "First task for today", Created: time.Now(), Due: time.Now().Add(time.Hour * 24)})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Second task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Third task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fourth task for today", Created: time.Now(), Due: time.Now()})
	todos = append(todos, Todo{Id: bson.NewObjectId(), Task: "Fifth task for today", Created: time.Now(), Due: time.Now()})

	for _, todo := range todos {
		if _, err = collection.UpsertId(todo.Id, &todo); err != nil {
			panic(err)
		}
	}
	// START OMIT
	pipeline := []bson.M{
		{"$group": bson.M{
			"_id":   bson.M{"$dayOfYear": "$d"},
			"count": bson.M{"$sum": 1},
		}},
	}

	var (
		result  TodoDueCounts
		results []TodoDueCounts
	)

	iter := collection.Pipe(pipeline).Iter()
	for {
		if iter.Next(&result) {
			results = append(results, result)
		} else {
			break
		}
	}
	err = iter.Err()
	if err != nil {
		panic(err)
	}
	// END OMIT
	fmt.Printf("%# v", pretty.Formatter(results))
}