Skip to content

Instantly share code, notes, and snippets.

@mvmaasakkers
Created February 19, 2014 09:01
Show Gist options
  • Save mvmaasakkers/9088420 to your computer and use it in GitHub Desktop.
Save mvmaasakkers/9088420 to your computer and use it in GitHub Desktop.
Simple iteration of mongo documents
// This is an example program that iterates over all
// items in a mongodb collection in a memory safe way
package main
import (
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"fmt"
)
type Item struct {
Id string `bson:"_id,omitempty"`
Name string `bson:"name"`
Active bool `bson:"active"`
}
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("database").C("collection")
item := Item{}
find := c.Find(bson.M{})
items := find.Iter()
for items.Next(&item) {
fmt.Println(item.Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment