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

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架