dongyan1841 2019-06-19 05:43
浏览 707
已采纳

Golang和MongoDB:带过滤器的DeleteMany

I try to read and write and delete data from a Go application with the official mongodb driver for go (go.mongodb.org/mongo-driver).

Here is my struct I want to use:

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

I omit code to add to the collection as this is working find.

I can get a list of contacts with a specific contact_id using the following code (abbreviated):

filter := bson.D{}
cursor, err := contactCollection.Find(nil, filter)
for cur.Next(context.TODO()) {
  ...
}

This works and returns the documents. I thought about doing the same for delete or a matched get:

// delete - abbreviated
filter := bson.M{"contact_id": id}
result, _ := contactCollection.DeleteMany(nil, filter)
// result.DeletedCount is always 0, err is nil
if 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 complete
func 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)
}

Why does the same filter does not work on delete?

Edit: Insert code looks like this:

_, _ = contactCollection.InsertOne(context.TODO(), Contact{
    ID: "abcdefg",
    SurName: "Demo",
    PreName: "on stackoverflow",
})
  • 写回答

2条回答 默认 最新

  • dps43378 2019-06-19 07:50
    关注

    Contact.ID is of type xid.ID, which is a byte array:

    type ID [rawLen]byte
    

    So the insert code you provided where you use a string literal to specify the value for the ID field would be a compile-time error:

    _, _ = contactCollection.InsertOne(context.TODO(), Contact{
        ID: "abcdefg",
        SurName: "Demo",
        PreName: "on stackoverflow",
    })
    

    Later in your comments you clarified that the above insert code was just an example, and not how you actually do it. In your real code you unmarshal the contact (or its ID field) from a request.

    xid.ID has its own unmarshaling logic, which might interpret the input data differently, and might result in an ID representing a different string value than your input. ID.UnmarshalJSON() defines how the string ID will be converted to 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])
    }
    

    As you can see, the first byte is cut off, and ID.UnmarshalText() does even more "magic" on it (check the source if you're interested).

    All-in-all, to avoid such "transformations" happen in the background without your knowledge, use a simple string type for your ID, and do necessary conversions yourself wherever you need to store / transmit your ID.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格