func getHw1(number int) string { conn, err := mongo.Dial("localhost") if err != nil { fmt.Println("Error trying to connect to database") } defer conn.Close() db := mongo.Database{conn, "m101", mongo.DefaultLastErrorCmd} funnynumbers := db.C("funnynumbers") cursor, err := funnynumbers.Find(nil).Limit(1).Skip(number).Sort(mongo.D{{"value", 1}}).Cursor() if err != nil { fmt.Println("Error trying to read collection") } defer cursor.Close() var value string if cursor.HasNext() { var m map[string]interface{} cursor.Next(&m) value = fmt.Sprint(m["value"]) } return value }
func main() { conn, err := mongo.Dial("localhost") if err != nil { fmt.Println("Error trying to connect to database") os.Exit(1) } defer conn.Close() db := mongo.Database{conn, "students", mongo.DefaultLastErrorCmd} grades := db.C("grades") cursor, err := grades.Find(mongo.M{"type": "homework"}).Sort(mongo.D{{"student_id", 1}, {"score", 1}}).Cursor() if err != nil { fmt.Println("Error trying to read collection") os.Exit(1) } defer cursor.Close() initialStudentId := -1 for cursor.HasNext() { var m map[string]interface{} cursor.Next(&m) studentId := m["student_id"] if initialStudentId != studentId { evict(m, &grades) initialStudentId = studentId.(int) } } }
// 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 chapter3(conn mongo.Conn) { log.Println("\n== CHAPTER 3 ==") db := mongo.Database{conn, "learn", mongo.DefaultLastErrorCmd} unicorns := db.C("unicorns") log.Println("\n== Find names of all unicorns. ==\n") cursor, err := unicorns.Find(nil).Fields(mongo.M{"name": 1}).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 12) log.Println("\n== Find all unicorns ordered by decreasing weight. ==\n") cursor, err = unicorns.Find(nil).Sort(mongo.D{{"weight", -1}}).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 12) log.Println("\n== Find all unicorns ordered by name and then vampire kills. ==\n") cursor, err = unicorns.Find(nil).Sort(mongo.D{{"name", 1}, {"vampires", -1}}).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 12) log.Println("\n== Find the 2nd and 3rd heaviest unicorns. ==\n") cursor, err = unicorns.Find(nil).Sort(mongo.D{{"weight", -1}}).Limit(2).Skip(1).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 2) log.Println("\n== Count unicorns with more than 50 kills. ==\n") n, err := unicorns.Find(mongo.M{"vampires": mongo.M{"$gt": 50}}).Count() if err != nil { log.Fatal(err) } if n != 6 { log.Fatalf("Got count=%d, want 6", n) } }
func main() { conn, err := mongo.Dial("localhost") if err != nil { fmt.Println("Error trying to connect to database") os.Exit(1) } defer conn.Close() db := mongo.Database{conn, "m101", mongo.DefaultLastErrorCmd} funnynumbers := db.C("funnynumbers") cursor, err := funnynumbers.Find(nil).Cursor() if err != nil { fmt.Println("Error trying to read collection") os.Exit(1) } defer cursor.Close() var magic int for cursor.HasNext() { var m map[string]interface{} cursor.Next(&m) value := int(m["value"].(float64)) if value%3 == 0 { magic += int(m["value"].(float64)) } } fmt.Println("The answer to Homework One, Problem 2 is", magic) }
func NewFollowersDatabase() *FollowersDatabase { conn, err := mongo.Dial("127.0.0.1:27017") if err != nil { log.Println("mongo Connect error:", err.Error()) panic("mongo conn err") } if verboseMongo { conn = mongo.NewLoggingConn(conn, log.New(os.Stderr, "", 0), "") } db := mongo.Database{conn, DbName, mongo.DefaultLastErrorCmd} return &FollowersDatabase{ userFollowers: db.C(USER_FOLLOWERS_TABLE), userFollowersCounter: db.C(USER_FOLLOWERS_COUNTERS_TABLE), followPending: db.C(FOLLOW_PENDING_TABLE), previousUnfollows: db.C(PREVIOUS_UNFOLLOWS_TABLE), } }
func main() { // create file file, err := os.Create("items.csv") if err != nil { panic(err) } defer file.Close() // Create CSV Writer writer := csv.NewWriter(file) // Connect to MongoDB conn, err := mongo.Dial("dharma.mongohq.com:10053") if err != nil { log.Fatal(err) } defer conn.Close() // Wrap the connection with a logger so that we can view traffic // to and from the mongoDB server // conn = mongo.NewLoggingConn(conn, log.New(os.Stdout, "", 0), "") // clear log prefix for more readable output log.SetFlags(0) // Create db object db := mongo.Database{conn, "nix_stagingv3", mongo.DefaultLastErrorCmd} err = db.Authenticate("sync", "vbnvbn45") if err != nil { log.Fatal(err) } // Create collections object items := db.C("items") // Auto Detect Headerline var m mongo.M err = items.Find(nil).One(&m) if err != nil && err != mongo.Done { log.Fatal(err) } // Create a cursor using Find query cursor, err := items.Find(nil).Cursor() if err != nil { log.Fatal(err) } defer cursor.Close() // Iterate over all items in a collection for cursor.HasNext() { var m mongo.M err := cursor.Next(&m) if err != nil { log.Fatal(err) } var record []string var header []string for k, _ := range m { s := fmt.Sprint(v) record = append(record, s) } writer.Write(record) writer.Flush() } }
func main() { // *host host := flag.String("host", "localhost:27017", "The host and port of the mongod instance you wish to connect to") dbname := flag.String("db", "testDB", "The output file that will be written to") user := flag.String("user", "", "The user you wish to authenticate with") pass := flag.String("pass", "", "The pass you wish to authenticate with") col := flag.String("col", "testCol", "The collection you wish to output") // fieldsFile := flag.String("fieldsFile", "~/", "The a file containing field names") // query := flag.String("query", "collection.csv", "The output file that will be written to") out := flag.String("out", "collection.csv", "The output file that will be written to") flag.Parse() // After cmd flag parse file, err := os.Create(*out) if err != nil { log.Fatal(err) } defer file.Close() // Create Writer writer := csv.NewWriter(file) // Connect to MongoDB conn, err := mongo.Dial(*host) if err != nil { log.Fatal(err) } defer conn.Close() // select DB db := mongo.Database{conn, *dbname, mongo.DefaultLastErrorCmd} // test for user and pass vars err = db.Authenticate(*user, *pass) if err != nil { log.Fatal(err) } // select Collection collection := db.C(*col) // Auto Detect Headerline var h mongo.M err = collection.Find(nil).One(&h) if err != nil { log.Fatal(err) } var headers []string for k, _ := range h { headers = append(headers, fmt.Sprint(k)) } // Default sort the headers // Otherwise accessing the headers will be // different each time. sort.Strings(headers) // write headers to file writer.Write(headers) writer.Flush() // log.Print(headers) // Create a cursor using Find query cursor, err := collection.Find(nil).Cursor() if err != nil { log.Fatal(err) } defer cursor.Close() // Iterate over all items in a collection for cursor.HasNext() { var m mongo.M err := cursor.Next(&m) if err != nil { log.Fatal(err) } var record []string for _, header := range headers { record = append(record, fmt.Sprint(m[header])) } writer.Write(record) writer.Flush() } }
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) } }
func chapter1(conn mongo.Conn) { log.Println("\n== CHAPTER 1 ==") // Create a database object. db := mongo.Database{conn, "learn", mongo.DefaultLastErrorCmd} // Create a collection object object for the "unicorns" collection. unicorns := db.C("unicorns") log.Println("\n== Add first unicorn. ==\n") err := unicorns.Insert(mongo.M{"name": "Aurora", "gender": "f", "weight": 450}) if err != nil { log.Fatal(err) } log.Println("\n== Find all unicorns. ==\n") cursor, err := unicorns.Find(nil).Cursor() if err != nil { log.Fatal(err) } log.Println("\n== Iterate over the documents in the result. ==\n") for cursor.HasNext() { var m mongo.M err := cursor.Next(&m) if err != nil { log.Fatal(err) } } log.Println("\n== Show index created on _id. ==\n") si := db.C("system.indexes") cursor, err = si.Find(nil).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "_id_") log.Println("\n== Insert a totally different document in unicorns. ==\n") err = unicorns.Insert(mongo.M{"name": "Leto", "gender": "m", "home": "Arrakeen", "worm": false}) if err != nil { log.Fatal(err) } cursor, err = unicorns.Find(nil).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Aurora", "Leto") log.Println("\n== Remove what we added to the database so far. ==\n") err = unicorns.Remove(nil) if err != nil { log.Fatal(err) } log.Println("\n== Add sample data for selector examples. ==\n") err = unicorns.Insert(chapter1SampleData...) if err != nil { log.Fatal(err) } log.Println("\n== Find all male unicorns that weight 700 pounds. ==\n") cursor, err = unicorns.Find(mongo.M{"gender": "m", "weight": mongo.M{"$gt": 700}}).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Unicrom", "Dunx") log.Println("\n== A similar query for demonstration purposes. ==\n") cursor, err = unicorns.Find(mongo.M{"gender": mongo.M{"$ne": "f"}, "weight": mongo.M{"$gte": 701}}).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Unicrom", "Dunx") log.Println("\n== Find unicorns without the vampires field. ==\n") cursor, err = unicorns.Find(mongo.M{"vampires": mongo.M{"$exists": false}}).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Nimue") log.Println("\n== Find female unicorns which either love apples or oranges or weigh less than 500 lbs. ==\n") cursor, err = unicorns.Find(mongo.M{ "gender": "f", "$or": mongo.A{ mongo.M{"loves": "apple"}, mongo.M{"loves": "orange"}}}).Cursor() if err != nil { log.Fatal(err) } expectFieldValues(cursor, "name", "Solnara", "Leia") }
func chapter2(conn mongo.Conn) { log.Println("\n== CHAPTER 2 ==") db := mongo.Database{conn, "learn", mongo.DefaultLastErrorCmd} unicorns := db.C("unicorns") hits := db.C("hits") log.Println("\n== Change Roooooodles' weight. ==\n") err := unicorns.Update(mongo.M{"name": "Roooooodles"}, mongo.M{"weight": 590}) if err != nil { log.Fatal(err) } log.Println("\n== Update replaced the document. ==\n") var m mongo.M err = unicorns.Find(mongo.M{"name": "Roooooodles"}).One(&m) if err != nil && err != mongo.Done { log.Fatal(err) } log.Println("\n== Reset the lost fields using the set operator. ==\n") err = unicorns.Update(mongo.M{"weight": 590}, mongo.M{"$set": mongo.M{ "name": "Roooooodles", "dob": dateTime(1979, 7, 18, 18, 44), "loves": mongo.A{"apple"}, "gender": "m", "vampires": 99}}) if err != nil { log.Fatal(err) } m = nil err = unicorns.Find(mongo.M{"name": "Roooooodles"}).One(&m) if err != nil { log.Fatal(err) } if m["name"] != "Roooooodles" { log.Fatal("Did not find Roooooodles") } log.Println("\n== Update weight the correct way. ==\n") err = unicorns.Update(mongo.M{"name": "Roooooodles"}, mongo.M{"$set": mongo.M{"weight": 590}}) if err != nil { log.Fatal(err) } m = nil err = unicorns.Find(mongo.M{"name": "Roooooodles"}).One(&m) if err != nil { log.Fatal(err) } if m["weight"] != 590 { log.Fatalf("Expected Roooooodles' weight=590, got %d\n", m["weight"]) } log.Println("\n== Correct the kill count for Pilot. ==\n") err = unicorns.Update(mongo.M{"name": "Pilot"}, mongo.M{"$inc": mongo.M{"vampires": -2}}) if err != nil { log.Fatal(err) } m = nil err = unicorns.Find(mongo.M{"name": "Pilot"}).One(&m) if err != nil { log.Fatal(err) } if m["vampires"] != 52 { log.Fatalf("Expected Pilot's vampires=52, got %d\n", m["vampires"]) } log.Println("\n== Aurora loves sugar. ==\n") err = unicorns.Update(mongo.M{"name": "Aurora"}, mongo.M{"$push": mongo.M{"loves": "sugar"}}) if err != nil { log.Fatal(err) } m = nil err = unicorns.Find(mongo.M{"name": "Aurora"}).One(&m) if err != nil { log.Fatal(err) } log.Println("\n== Updating a missing document does nothing. ==\n") err = hits.Update(mongo.M{"page": "unicorns"}, mongo.M{"$inc": mongo.M{"hits": 1}}) if err == nil || err != mongo.ErrNotFound { log.Fatal(err) } err = hits.Find(mongo.M{"page": "unicorns"}).One(&m) if err != nil && err != mongo.Done { log.Fatal(err) } log.Println("\n== Upsert inserts the document if missing. ==\n") err = hits.Upsert(mongo.M{"page": "unicorns"}, mongo.M{"$inc": mongo.M{"hits": 1}}) if err != nil { log.Fatal(err) } err = hits.Find(mongo.M{"page": "unicorns"}).One(&m) if err != nil { log.Fatal(err) } log.Println("\n== Upsert updates the document if already present. ==\n") err = hits.Upsert(mongo.M{"page": "unicorns"}, mongo.M{"$inc": mongo.M{"hits": 1}}) if err != nil { log.Fatal(err) } err = hits.Find(mongo.M{"page": "unicorns"}).One(&m) if err != nil { log.Fatal(err) } log.Println("\n== Update updates a single document. ==\n") err = unicorns.Update(nil, mongo.M{"$set": mongo.M{"vaccinated": true}}) if err != nil { log.Fatal(err) } cursor, err := unicorns.Find(mongo.M{"vaccinated": true}).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 1) log.Println("\n== UpdateAll updates all documents. ==\n") err = unicorns.UpdateAll(nil, mongo.M{"$set": mongo.M{"vaccinated": true}}) if err != nil { log.Fatal(err) } cursor, err = unicorns.Find(mongo.M{"vaccinated": true}).Cursor() if err != nil { log.Fatal(err) } expectCount(cursor, 12) }