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) } } }
func Example() { // Connect to server. conn, err := mongo.Dial("localhost") if err != nil { log.Fatal(err) } defer conn.Close() c := mongo.Collection{conn, "example-db.example-collection", mongo.DefaultLastErrorCmd} // Insert a document. id := mongo.NewObjectId() err = c.Insert(&ExampleDoc{Id: id, Title: "Hello", Body: "Mongo is fun."}) if err != nil { log.Fatal(err) } // Find the document. var doc ExampleDoc err = c.Find(map[string]interface{}{"_id": id}).One(&doc) if err != nil { log.Fatal(err) } log.Print(doc.Title, " ", doc.Body) }
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 (c *FollowersDatabase) Reconnect() { log.Printf("reconnecting, just in case") conn, err := mongo.Dial("127.0.0.1:27017") if err != nil { log.Println("mongo Connect error:", err.Error()) panic("mongo conn err") } c.userFollowers.Conn = conn c.userFollowersCounter.Conn = conn c.followPending.Conn = conn c.previousUnfollows.Conn = conn }
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), } }
// A function that Dials and Authenticates // into a provided data base // accespts host,db,user,pass,log=Bool // returns db,err func ConnAndAuth(h, d, u, p string, l bool) mongo.Database { conn, err := mongo.Dial(h) if err != nil { log.Fatal(err) } defer conn.Close() if l { conn = mongo.NewLoggingConn(conn, log.New(os.Stdout, "", 0), "") // clear log prefix for more readable output log.SetFlags(0) } db := mongo.Database{conn, d, mongo.DefaultLastErrorCmd} err = db.Authenticate(u, p) if err != nil { log.Fatal(err) } return db }
func main() { // Connect to server. conn, err := mongo.Dial("localhost") if err != nil { log.Fatal(err) } defer conn.Close() // Wrap connection with logger so that we can view the traffic to and from // the server. conn = mongo.NewLoggingConn(conn, log.New(os.Stdout, "", 0), "") // Clear the log prefix for more readable output. log.SetFlags(0) reset(conn) chapter1(conn) chapter2(conn) chapter3(conn) chapter7(conn) }
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 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() } }