MongoDB是Nosql中常用的一种数据库,今天笔者就简单总结一下Golang如何使用这些通用的供能的,不喜勿喷。。。
研究的事例结构如下:
type LikeBest struct {
AuthorName string `bson:"authorname,omitempty"`
BookName string `bson:"bookname,omitempty"`
PublishTime string `bson:"publishtime,omitempty"`
LastReadTime string `bson:"lastreadtime,omitempty"`
}
type Personnal struct {
UserName string `bson:"username,omitempty"`
WhereCity string `bson:"wherecity,omitempty"`
BookSCount int `bson:"bookscount,omitempty"`
FavoriteBooks []LikeBest `bson:"favoratebooks,omitempty"`
}
建立与MongoDB的连接
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("PersonManage").C("Persons")
注意:以下操作条件默认均为:username=”impressionw”
插入数据
1、使用Insert()函数是最简单且通用的方式
err := c.Insert(&p) //p为插入的结构体数据
2、使用upsert()函数【更新或插入】
change := mgo.Change{
Update: bson.M{
"$set": p},
ReturnNew: false,
Remove: false,
Upsert: true,
}
_, err := c.Find(bson.M{
"username": "impressionw"}).Apply(change, nil)
或许,你觉得第一种方式更简洁,但是实际场景中,第二种也非常实用
1. 它不仅只能插入数据,Update字段可以接收多个参数插入,但是关键字不能相同【不能同时有2个”$set”】
2. 它能返回处理前或处理后的document,若返回,则Apply的第二个参数即是结果
3. 它可以结合select使用
注意:$set 只修改指定字段的值,不影响其他值
查询数据
1、查询整个文档
err = c.Find(bson.M{
"username": "impressionw"}).One(&result)
2、只返回 FavoriteBooks 对应的字段,忽略其他信息
这里用到了Select(),select可以设置,返回的内容:
- select{‘filedname’:0},表示忽略该字段则结果不返回此字段
- select{‘filedname’:1},表示关注该字段则只返回关注字段
err = c.Find(bson.M{
"username": "impressionw"}).Select(bson.M{
"favoratebooks": 1}).One(&result)
3、查询文档的_id
var result interface{}
err = c.Find(bson.M{
"username": "impressionw"}).Select(bson.M{
"_id": 1}).One(&result)
var document_id string
switch value := result.(type) {
case bson.M:
mapid := value["_id"]
if mapid != nil {
id := mapid.(bson.ObjectId)
document_id = id.Hex()
}
}
注意:若是查找username含有”impressionw”的文档,可用正则匹配查找,条件这样写:
query = bson.M{
"username": bson.M{
"$regex": "impressionw"}}