// reset cleans up after previous runs of this applications. func reset(conn mongo.Conn) { log.Println("\n== Clear documents and indexes created by previous run. ==\n") db := mongo.Database{conn, "learn", mongo.DefaultLastErrorCmd} db.Run(mongo.D{{"profile", 0}}, nil) db.C("unicorns").Remove(nil) db.C("hits").Remove(nil) db.Run(mongo.D{{"dropIndexes", "unicorns"}, {"index", "*"}}, nil) db.Run(mongo.D{{"dropIndexes", "hits"}, {"index", "*"}}, nil) }
func chapter7(conn mongo.Conn) { log.Println("\n== CHAPTER 7 ==") db := mongo.Database{conn, "learn", mongo.DefaultLastErrorCmd} unicorns := db.C("unicorns") log.Println("\n== Create index on name. ==\n") err := unicorns.CreateIndex(mongo.D{{"name", 1}}, nil) if err != nil { log.Fatal(err) } log.Println("\n== Drop index on name. ==\n") err = db.Run(mongo.D{ {"dropIndexes", unicorns.Name()}, {"index", mongo.IndexName(mongo.D{{"name", 1}})}, }, nil) if err != nil { log.Fatal(err) } log.Println("\n== Create unique index on name. ==\n") err = unicorns.CreateIndex(mongo.D{{"name", 1}}, &mongo.IndexOptions{Unique: true}) if err != nil { log.Fatal(err) } log.Println("\n== Create compound index on name ascending and kills descending. ==\n") err = unicorns.CreateIndex(mongo.D{{"name", 1}, {"vampires", -1}}, nil) if err != nil { log.Fatal(err) } log.Println("\n== Explain query. ==\n") var m mongo.M err = unicorns.Find(nil).Explain(&m) if err != nil { log.Fatal(err) } log.Println("\n== Explain query on name. ==\n") m = nil err = unicorns.Find(mongo.M{"name": "Pilot"}).Explain(&m) if err != nil { log.Fatal(err) } log.Println("\n== Enable profiling. ==\n") err = db.Run(mongo.D{{"profile", 2}}, nil) if err != nil { log.Fatal(err) } log.Println("\n== Get profile data for query. ==\n") cursor, err := unicorns.Find(mongo.M{"weight": mongo.M{"$gt": 600}}).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Unicrom", "Ayna", "Kenny", "Leia", "Pilot", "Dunx") cursor, err = db.C("system.profile").Find(nil).Cursor() if err != nil { log.Fatal(err) } for cursor.HasNext() { var m mongo.M err := cursor.Next(&m) if err != nil { log.Fatal(err) } } cursor.Close() log.Println("\n== Profile queries that take longer than 100 ms. ==\n") err = db.Run(mongo.D{{"profile", 2}, {"slowms", 100}}, nil) if err != nil { log.Fatal(err) } }