溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MongoDB怎么在Golang中使用

發(fā)布時間:2020-12-28 14:24:01 來源:億速云 閱讀:204 作者:Leah 欄目:開發(fā)技術(shù)

MongoDB怎么在Golang中使用?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

研究的事例結(jié)構(gòu)如下:

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")

注意:以下操作條件默認(rèn)均為:username=”impressionw”

插入數(shù)據(jù)

1、使用Insert()函數(shù)是最簡單且通用的方式

err := c.Insert(&p) //p為插入的結(jié)構(gòu)體數(shù)據(jù)

2、使用upsert()函數(shù)【更新或插入】

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. 它不僅只能插入數(shù)據(jù),Update字段可以接收多個參數(shù)插入,但是關(guān)鍵字不能相同【不能同時有2個”$set”】
? ? ? ? 2. 它能返回處理前或處理后的document,若返回,則Apply的第二個參數(shù)即是結(jié)果
? ? ? ? 3. 它可以結(jié)合select使用

注意:$set 只修改指定字段的值,不影響其他值

查詢數(shù)據(jù)

1、查詢整個文檔

err = c.Find(bson.M{"username": "impressionw"}).One(&result)

2、只返回 FavoriteBooks 對應(yīng)的字段,忽略其他信息
? ? 這里用到了Select(),select可以設(shè)置,返回的內(nèi)容:

select{‘filedname':0},表示忽略該字段則結(jié)果不返回此字段
select{‘filedname':1},表示關(guān)注該字段則只返回關(guān)注字段
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、查詢數(shù)組中匹配元素,只返回含有匹配元素的文檔,需要用到Mongdob的聚合aggregate

? ? 相關(guān)操作符的含義如下:

  • $project:修改輸入文檔的結(jié)構(gòu)??梢杂脕碇孛?、增加或刪除域,也可以用于創(chuàng)建計算結(jié)果以及嵌套文檔。

  • match:用于過濾數(shù)據(jù),只輸出符合條件的文檔。match使用MongoDB的標(biāo)準(zhǔn)查詢操作。

  • $limit:用來限制MongoDB聚合管道返回的文檔數(shù)。

  • $skip:在聚合管道中跳過指定數(shù)量的文檔,并返回余下的文檔。

  • $unwind:將文檔中的某一個數(shù)組類型字段拆分成多條,每條包含數(shù)組中的一個值。

  • $group:將集合中的文檔分組,可用于統(tǒng)計結(jié)果。

  • $sort:將輸入文檔排序后輸出。

  • $geoNear:輸出接近某一地理位置的有序文檔。

下面的代碼,將只返回FavorateBooks字段中,bookname為”The Go Programming Language”的書籍,且只關(guān)注favoratebooks,不會輸出個人信息

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)

這樣可以達(dá)到目的了

更新文檔

1、更新WhereCity字段—關(guān)鍵字 $set,將WhereCity修改為”ShangHai“:

err = c.Update(bson.M
{"username": "impressionw"
}, 
bson.M{"$set": bson.M
{"wherecity": "ShangHai"
}})

2、更新FavoriteBooks中的LastReadTime字段

? ?查詢條件:username=”impressionw”、bookname=”The Go Programming Language”,將LastReadTime字段更改為:”O(jiān)ct 26, 2017”

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 的整個數(shù)組文檔,即新增一本書的信息
? ?? ?給username=”impressionw”的文檔新增一條書籍記錄,同時將BookSCount字段自增1

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不會添加已有的數(shù)據(jù),push 會添加重復(fù)的數(shù)據(jù),可以分別應(yīng)用于不同場景
2、$inc 對文檔的某個值為數(shù)字型(只能為滿足要求的數(shù)字)的鍵進(jìn)行增減的操作, 值為正數(shù)表示自增,值為負(fù)數(shù)表示自減

刪除文檔

1、刪除喜歡的一本書籍信息,同時喜歡書記數(shù)量自減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、刪除整個文檔,根據(jù)”_id”字段刪除文檔

err := session.DB("PersonManage").C("Persons").Remove(bson.M
{"_id":bson.ObjectIdHex("

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI