Created
June 22, 2014 02:10
-
-
Save moongears/3861caffd79010e930ea to your computer and use it in GitHub Desktop.
Golang Mongo find
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
package main | |
import ( | |
"fmt" | |
"time" | |
"os" | |
"labix.org/v2/mgo" | |
"labix.org/v2/mgo/bson" | |
) | |
type Person struct { | |
ID bson.ObjectId `bson:"_id,omitempty"` | |
Name string `bson:"nm"` | |
Phone string `bson:"ph"` | |
created time.Time `bson:"c,omitempty"` | |
} | |
func main() { | |
//get session | |
session, err := mgo.Dial("localhost") | |
if err != nil { | |
fmt.Printf("dial fail %v\n", err) | |
os.Exit(1) | |
} | |
defer session.Close() | |
//error check on every access | |
session.SetSafe(&mgo.Safe{}) | |
//find record | |
var person Person | |
err = session.DB("test_db").C("people").Find(bson.M{"nm": "Gordon Sumner"}).One(&person) | |
if err != nil { | |
fmt.Printf("find fail %v\n", err) | |
os.Exit(1) | |
} | |
fmt.Printf("find #1: person %v\n", person) | |
err = session.DB("test_db").C("people").Find(bson.M{"nm": bson.M{"$regex": bson.RegEx{`Andy.*`, ""}}}).One(&person) | |
if err != nil { | |
fmt.Printf("find fail %v\n", err) | |
os.Exit(1) | |
} | |
fmt.Printf("find #2: person %v\n", person) | |
var people []Person | |
err = session.DB("test_db").C("people").Find(bson.M{"ph": bson.M{"$regex": bson.RegEx{`^\+11.*`, ""}}}).All(&people) | |
if err != nil { | |
fmt.Printf("find fail %v\n", err) | |
os.Exit(1) | |
} | |
fmt.Printf("find #3: people %v\n", people) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment