MongoDB Mgo
type Person struct {
Name string
Phone string
}
Search One
err = c.Find(bson.M{"name": "馬力"}).One(&result)
Search All in List
results := []Person{}
err = c.Find(bson.M{"name": "馬力"}).All(&results)
if err != nil {
log.Fatal(err)
}
for _, j := range results {
fmt.Println("Phone:", j.Phone)
//fmt.Println("Phone:", results)
}
Sort By TimeStamp (If Have)
err = c.Find(bson.M{"name": "馬力"}).Sort("-timestamp").All(&results)
Seach Pattern
search "台北" as as a search patten.
presult := Person{}
err = c.Find(bson.M{"phone": bson.RegEx{Pattern: "台北", Options: "i"}}).One(&presult)
check Number of search result
num, _ := c.Find(bson.M{"id": searchid}).Count()
Delete Data
c.Remove(bson.M{"id": searchid})
Update Data
updateTarget := bson.M{"id": searchid}
change := bson.M{"$set": bson.M{"phone": "新phone"}}
if err := c.Update(updateTarget, change); err != nil {
fmt.Println("update error:", err)
}
It update local data, phone, and keep rest of all data.
Drop Database
sDroped := session.DB("test").DropDatabase()
No comments:
Post a Comment