golang學習之mgo操作mongodb

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

mgo是mongodb的golang驅動,測試代碼:

// mgotest project main.gopackage main import ( "fmt"    "time"    "gopkg.in/mgo.v2"    "gopkg.in/mgo.v2/bson" ) type User struct { Id bson.ObjectId `bson:"_id"` Username string `bson:"name"` Pass string `bson:"pass"` Regtime int64 `bson:"regtime"` Interests []string `bson:"interests"` } const URL String = "127.0.0.1:27017" var c *mgo.Collection var session *mgo.Session func (user User) ToString() string { return fmt.Sprintf("%#v", user) } func init() { session, _ = mgo.Dial(URL) //切換到資料庫    db := session.DB("blog") //切換到collection    c = db.C("mgotest") } //新增資料func add() { // defer session.Close()    stu1 := new(User) stu1.Id = bson.NewObjectId() stu1.Username = "stu1_name" stu1.Pass = "stu1_pass" stu1.Regtime = time.Now().Unix() stu1.Interests = []string{"象棋", "遊泳", "跑步"} err := c.Insert(stu1) if err == nil { fmt.Println("插入成功") } else { fmt.Println(err.Error()) defer panic(err) } } //查詢func find() { // defer session.Close() var users []User // c.Find(nil).All(&users)    c.Find(bson.M{"name": "stu1_name"}).All(&users) for _, value := range users { fmt.Println(value.ToString()) } //根據ObjectId進行查詢    idStr := "577fb2d1cde67307e819133d" objectId := bson.ObjectIdHex(idStr) user := new(User) c.Find(bson.M{"_id": objectId}).One(user) fmt.Println(user) } //根據id進行修改func update() { interests := []string{"象棋", "遊泳", "跑步"} err := c.Update(bson.M{"_id": bson.ObjectIdHex("577fb2d1cde67307e819133d")}, bson.M{"$set": bson.M{ "name":      "修改後的name", "pass":      "修改後的pass", "regtime": time.Now().Unix(), "interests": interests, }}) if err != nil { fmt.Println("修改失敗") } else { fmt.Println("修改成功") } } //刪除func del() { err := c.Remove(bson.M{"_id": bson.ObjectIdHex("577fb2d1cde67307e819133d")}) if err != nil { fmt.Println("刪除失敗" + err.Error()) } else { fmt.Println("刪除成功") } } func main() { add() find() update() del() }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.