亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 和 MongoDB:帶過濾器的DeleteMany

Golang 和 MongoDB:帶過濾器的DeleteMany

Go
慕桂英4014372 2023-06-26 16:40:59
我嘗試使用 Go 的官方 mongodb 驅動程序 (go.mongodb.org/mongo-driver) 從 Go 應用程序讀取、寫入和刪除數據。這是我想使用的結構:Contact struct {    ID               xid.ID `json:"contact_id" bson:"contact_id"`    SurName          string `json:"surname" bson:"surname"`    PreName          string `json:"prename" bson:"prename"`}// xid is https://github.com/rs/xid我省略了添加到集合中的代碼,因為這是工作查找。我可以使用以下代碼(縮寫)獲取具有特定 contact_id 的聯系人列表:filter := bson.D{}cursor, err := contactCollection.Find(nil, filter)for cur.Next(context.TODO()) {  ...}這將起作用并返回文檔。我考慮過對刪除或匹配的獲取執行相同的操作:// delete - abbreviatedfilter := bson.M{"contact_id": id}result, _ := contactCollection.DeleteMany(nil, filter)// result.DeletedCount is always 0, err is nilif err != nil {    sendError(c, err) // helper function    return}c.JSON(200, gin.H{    "ok":      true,    "message": fmt.Sprintf("deleted %d patients", result.DeletedCount),}) // will be called, it is part of a webservice done with gin// get completefunc Get(c *gin.Context) {    defer c.Done()    id := c.Param("id")    filter := bson.M{"contact_id": id}    cur, err := contactCollection.Find(nil, filter)    if err != nil {        sendError(c, err) // helper function        return    } // no error    contacts := make([]types.Contact, 0)    for cur.Next(context.TODO()) { // nothing returned        // create a value into which the single document can be decoded        var elem types.Contact        err := cur.Decode(&elem)        if err != nil {            sendError(c, err) // helper function            return        }        contacts = append(contacts, elem)    }    c.JSON(200, contacts)}為什么相同的過濾器在刪除時不起作用?編輯:插入代碼如下所示:_, _ = contactCollection.InsertOne(context.TODO(), Contact{    ID: "abcdefg",    SurName: "Demo",    PreName: "on stackoverflow",})
查看完整描述

2 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

Contact.ID類型為xid.ID,它是一個字節數組:

type?ID?[rawLen]byte

string因此,您提供的使用文字指定字段值的插入代碼ID將是編譯時錯誤:

_, _ = contactCollection.InsertOne(context.TODO(), Contact{

? ? ID: "abcdefg",

? ? SurName: "Demo",

? ? PreName: "on stackoverflow",

})

后來在您的評論中,您澄清了上面的插入代碼只是一個示例,而不是您實際的操作方式。在您的真實代碼中,您從請求中解組聯系人(或其 ID 字段)。

xid.ID有其自己的解組邏輯,這可能會以不同的方式解釋輸入數據,并可能導致 ID 表示string與您的輸入不同的值。ID.UnmarshalJSON()定義stringID 如何轉換為xid.ID

func (id *ID) UnmarshalJSON(b []byte) error {

? ? s := string(b)

? ? if s == "null" {

? ? ? ? *id = nilID

? ? ? ? return nil

? ? }

? ? return id.UnmarshalText(b[1 : len(b)-1])

}

正如您所看到的,第一個字節被截斷,并且ID.UnmarshalText()對其進行了更多“魔法”(如果您感興趣,請檢查源代碼)。

總而言之,為了避免在您不知情的情況下在后臺發生此類“轉換”,請string為您的 ID 使用簡單的類型,并在需要存儲/傳輸您的 ID 的任何地方自行進行必要的轉換。


查看完整回答
反對 回復 2023-06-26
?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

對于 ID 字段,您應該使用primitive.ObjectIDbson 包提供的。


"go.mongodb.org/mongo-driver/bson/primitive"


ID          primitive.ObjectID `json:"_id" bson:"_id"`


查看完整回答
反對 回復 2023-06-26
  • 2 回答
  • 0 關注
  • 347 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號