(编辑:jimmy 日期: 2024/12/24 浏览:2)
MongoDB是Nosql中常用的一种数据库,今天笔者就简单总结一下Golang如何使用这些通用的供能的,不喜勿喷。。。
"htmlcode">
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)
"htmlcode">
err = c.Find(bson.M{"username": "impressionw"}).One(&result)
2、只返回 FavoriteBooks 对应的字段,忽略其他信息
"htmlcode">
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"}}
4、查询数组中匹配元素,只返回含有匹配元素的文档,需要用到Mongdob的聚合aggregate
"htmlcode">
pipe := c.Pipe([]bson.M{{"$unwind": "$favoratebooks"}, {"$match": bson.M{"username": "impressionw", "favoratebooks.bookname": "The Go Programming Language"}}, {"$project": bson.M{"favoratebooks": 1}}}) resp := []bson.M{} err := pipe.All(&resp)
这样可以达到目的了
1、更新WhereCity字段—关键字 $set,将WhereCity修改为”ShangHai“:
err = c.Update(bson.M {"username": "impressionw" }, bson.M{"$set": bson.M {"wherecity": "ShangHai" }})
2、更新FavoriteBooks中的LastReadTime字段
"htmlcode">
change := mgo.Change{ Update: bson.M{"$set": bson.M{"favoratebooks.$.lastreadtime": "Oct 26, 2017"}}, ReturnNew: false, Remove: false, Upsert: true, } query := bson.M{"username": "impressionw", "favoratebooks": bson.M{"$elemMatch": bson.M{"bookname": "The Go Programming Language"}}} _, err = c.Find(query).Select(bson.M{"favoratebooks.bookname": 1}).Apply(change, nil)
3、更新一个 FavoriteBooks 的整个数组文档,即新增一本书的信息
"htmlcode">
Act := []LikeBest{ LikeBest{ AuthorName: "YuHen", BookName: "Go Learning", PublishTime: "Dec 27, 2014", LastReadTime: "Dec 29, 2016", }, } change := mgo.Change{ Update: bson.M{"$inc": bson.M{"bookscount": 1}, "$push": bson.M{"favoratebooks": bson.M{"$each": Act}}}, ReturnNew: false, Remove: false, Upsert: true, } _, err := c.Find(bson.M{"username": "impressionw"}).Apply(change, nil)
注意:
1、此处可用addToSet代替push,addToSet不会添加已有的数据,push 会添加重复的数据,可以分别应用于不同场景
2、$inc 对文档的某个值为数字型(只能为满足要求的数字)的键进行增减的操作, 值为正数表示自增,值为负数表示自减
1、删除喜欢的一本书籍信息,同时喜欢书记数量自减1
var option = bson.M {"$pull": bson.M{"favoratebooks": bson.M{"bookname": "Go Learning"}}, "$inc": bson.M{"bookscount": -1}} err := c.Update(bson.M{"username": "impressionw"}, option)
2、删除所有喜欢的书籍,同时将bookscount字段置为 0
var data = bson.M{"$unset": bson.M {"favoratebooks": true}, "$set": bson.M{"bookscount": 0}} err = c.Update(bson.M {"username": "impressionw"}, data)
3、删除整个文档,根据”_id”字段删除文档
err := session.DB("PersonManage").C("Persons").Remove(bson.M {"_id":bson.ObjectIdHex("