登录
首页 >  Golang >  Go问答

使用Golang删除MongoDB中的多个文档,并带有过滤器

来源:stackoverflow

时间:2024-03-26 16:30:35 190浏览 收藏

使用 Go MongoDB 驱动程序时,开发者在删除具有特定过滤器条件的文档时遇到问题。问题源于 contact.id 类型为 xid.ID(字节数组),而插入代码将 id 指定为字符串文字,导致编译时错误。解决方案是使用 string 类型并自行进行转换,或者使用 bson 包提供的 primitive.ObjectID 类型。

问题内容

我尝试使用 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 - 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)
}

为什么相同的过滤器在删除时不起作用?

编辑:插入代码如下所示:

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

解决方案


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() 定义了如何将 string id 转换为 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() 在它上面做了更多“魔法”(如果您感兴趣,请检查源代码)。

总而言之,为了避免在您不知情的情况下在后台发生此类“转换”,请为您的 id 使用简单的 string 类型,并在需要存储/传输您的 id 的任何地方自行进行必要的转换。

对于 id 字段,您应该使用 bson 包提供的 primitive.objectid

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

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>