mgo
是mongodb
的go語言綁定,第一次在靜態類型語言中使用ORM,故留個筆記。git
mongodb
是schema-less
無模式的NoSQL
非關係型數據庫,理論上來講,在同一個表(mongodb
中稱爲collection
)中的行(mongodb
稱爲document
)也可能具備不一樣的字段。github
簡單的模型能夠如此定義。golang
type Article struct { Id bson.ObjectId `bson:"_id,omitempty"` Title string `bson:"title"` Content string `bson:"content"` }
使用了struct field tag
,參考golang英文wiki,還有這裏的golang spec。mongodb
其中Id
這個字段是使用mongodb
本身生成的_id
字段,omitempty
表示該字段在序列化的時候只接受非零值(0,空slice,或者空map都算是零值),按照個人理解就是,若是Id
是0
,那麼過了Marshal
以後應該是見不到_id
這個字段的。shell
這個設計保證了不會誤存go語言給Id
的默認值0
,形成鍵衝突。數據庫
bson:"<field_name>"
和json:"<field_name>"
相似,聲明瞭序列化後字段的鍵名。json
回到正題,簡單字段如int32
、float32
、string
都不須要特殊處理,時間多是一個須要關注的地方。c#
type Article struct { Id bson.ObjectId `bson:"_id,omitempty"` CreatedAt time.Time `bson:"created_at"` UpdatedAt time.Time `bson:"updated_at"` Title string `bson:"title"` Content string `bson:"content"` }
注意的一個點是bson.MongoTimestamp
在我使用時出現了沒法正確反序列化mongodb
查詢結果的問題,緣由不明。數據是手動在mongo shell
裏插入的,使用new Date()
賦值了created_at
和updated_at
。有人知道怎麼回事的話請告訴我。less
使用time.Time
就能夠正常序列化了。設計
mgo
查詢基本思路是:建立鏈接(mgo.Dial
)、選擇數據庫(Session.DB
)、選擇集合(Database.C
)、設置條件(Collection.Find
)、取出結果(Query.All
)。
簡單例子以下。
func findSomething() { sess, err := mgo.Dial("mongodb://localhost:27017") if err != nil { panic(err) } var result []Article sess.DB("test").C("articles").Find(bson.M{"title": "mgo初接觸"}).All(&result) fmt.Println(result) }
和通常mongo
查詢同樣支持一些排序之類的操做。
Query.Sort
按照文檔說法能夠寫出這樣的查詢:Find(bson.M{}).Sort("-created_at")
,-
號表示降序。
Query.skip
能夠跳過必定數量的結果,Query.One
表示只取一個元素,Query.Limit
限制查詢結果的數量等等...
寫入的基本操做是Collection.Insert
和Collection.Update
以及兩個變體Collection.UpdateId
以及Collection.UpdateAll
。
最基本的Collection.Insert
應該不用多解釋。
Collection.Update
按照文檔描述,是查找到匹配參數selector
條件的一個document
並更新。一般咱們更新document
應該是用_id
字段來惟一肯定,顧名思義Collection.UpdateId
就是這樣一個便捷方法。
更新多個document
的時候就用到了Collection.UpdateAll
了。參數和Collection.Update
無異,selector
肯定要更新的document
有哪些,update
參數則肯定要更新到什麼樣子。