Skip to content

Instantly share code, notes, and snippets.

@d3sire
Last active March 2, 2016 03:32
Show Gist options
  • Save d3sire/628d4cd180ad9a6cad0d to your computer and use it in GitHub Desktop.
Save d3sire/628d4cd180ad9a6cad0d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
"time"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Phone string
Timestamp time.Time
}
var (
IsDrop = true
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
// Drop Database
if IsDrop {
err = session.DB("test").DropDatabase()
if err != nil {
panic(err)
}
}
// Collection People
c := session.DB("test").C("people")
// Index
index := mgo.Index{
Key: []string{"name", "phone"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = c.EnsureIndex(index)
if err != nil {
panic(err)
}
people := make([]Person, 5)
for i := 0; i < 5; i++ {
phone := "+55 53 1234 4321" + strconv.Itoa(i)
people[i] = Person{
Name: "Ale", Phone: phone, Timestamp: time.Now()}
}
bulk := c.Bulk()
bulk.Unordered()
bulk.Insert(&people)
_, err = bulk.Run()
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment