Created
June 22, 2014 07:13
-
-
Save moongears/e09c9e4406433a7ec416 to your computer and use it in GitHub Desktop.
Golang Mongo update
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{}) | |
//get collection | |
coll := session.DB("test_db").C("people") | |
//find record | |
var person Person | |
err = coll.Find(bson.M{"nm": "Gordon Sumner"}).One(&person) | |
if err != nil { | |
fmt.Printf("find fail %v\n", err) | |
os.Exit(1) | |
} | |
err = coll.Update(bson.M{"_id": person.ID}, bson.M{"$set": bson.M{"ph": "+99 99 9999 1111"}}) | |
if err != nil { | |
fmt.Printf("update fail %v\n", err) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment