Last active
August 29, 2015 14:02
-
-
Save varver/14d552338beac810827b to your computer and use it in GitHub Desktop.
Insert and retrieve data from mongodb with golang.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Insert and retrieve data from mongodb with golang . | |
*/ | |
package main | |
import ( | |
"fmt" | |
"labix.org/v2/mgo" | |
// "labix.org/v2/mgo/bson" | |
"time" | |
"log" | |
"io" | |
"math/rand" | |
) | |
type randbo struct { | |
rand.Source | |
} | |
// New creates a new random reader with a time source. | |
func New() io.Reader { | |
return NewFrom(rand.NewSource(time.Now().UnixNano())) | |
} | |
// NewFrom creates a new reader from your own rand.Source | |
func NewFrom(src rand.Source) io.Reader { | |
return &randbo{src} | |
} | |
// Read satisfies io.Reader | |
func (r *randbo) Read(p []byte) (n int, err error) { | |
todo := len(p) | |
offset := 0 | |
for { | |
val := int64(r.Int63()) | |
for i := 0; i < 8; i++ { | |
p[offset] = byte(val) | |
todo-- | |
if todo == 0 { | |
return len(p), nil | |
} | |
offset++ | |
val >>= 8 | |
} | |
} | |
} | |
type Person struct { | |
Name string | |
Phone string | |
} | |
func main() { | |
time1 := time.Now() | |
fmt.Println(time1) | |
session, err := mgo.Dial("0.0.0.0:27017") | |
if err != nil { | |
panic(err) | |
} | |
defer session.Close() | |
datasource := New() | |
buf := make([]byte, 32) | |
name_, _ := datasource.Read(buf) | |
phone_, _ := datasource.Read(buf) | |
name := string(name_) | |
phone := string(phone_) | |
// Optional. Switch the session to a monotonic behavior. | |
session.SetMode(mgo.Monotonic, true) | |
c := session.DB("test").C("people") | |
//people := []*Person{} | |
for i := 0; i < 1000000; i++ { | |
c.Insert(&Person{name, phone}) | |
if i%10000 == 0 { | |
log.Printf("Populated %d records", i) | |
} | |
} | |
fmt.Printf("done") | |
time2 := time.Since(time1) | |
fmt.Println(time2) | |
/* | |
//fmt.Printf(*people ...) | |
err = c.Insert(people ...) | |
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, | |
&Person{"Cla", "+55 53 8402 8510"}) | |
if err != nil { | |
panic(err) | |
} | |
result := Person{} | |
err = c.Find(bson.M{"name": "Ale"}).One(&result) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Phone:", result.Phone) | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment