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
参数则肯定要更新到什么样子。