Golang和MongoDB:使用过滤器删除多个
我尝试使用官方的Go mongodb驱动程序(Go.mongodb.org/mongodriver)从Go应用程序中读取、写入和删除数据 这是我要使用的结构:Golang和MongoDB:使用过滤器删除多个,mongodb,go,mongo-go,Mongodb,Go,Mongo Go,我尝试使用官方的Go mongodb驱动程序(Go.mongodb.org/mongodriver)从Go应用程序中读取、写入和删除数据 这是我要使用的结构: Contact struct { ID xid.ID `json:"contact_id" bson:"contact_id"` SurName string `json:"surname" bson:"surname"` PreName string
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
我省略了添加到集合中的代码,因为这是有效的查找
我可以使用以下代码(缩写)获得具有特定联系人id的联系人列表:
这将起作用并返回文档。我考虑对删除或匹配的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)
}
为什么同一个过滤器不能用于删除
编辑:插入代码如下所示:
_, _ = contactCollection.InsertOne(context.TODO(), Contact{
ID: "abcdefg",
SurName: "Demo",
PreName: "on stackoverflow",
})
Contact.ID
的类型为字节数组:
type ID [rawLen]byte
因此,使用字符串文本指定ID
字段的值时提供的插入代码将是编译时错误:
_, _ = contactCollection.InsertOne(context.TODO(), Contact{
ID: "abcdefg",
SurName: "Demo",
PreName: "on stackoverflow",
})
稍后在您的评论中,您澄清了上述插入代码只是一个示例,而不是您实际如何执行它。在实际代码中,您可以从请求中解组联系人(或其ID字段)
具有自己的解组逻辑,这可能会以不同的方式解释输入数据,并可能导致ID表示与您的输入不同的字符串
值。定义如何将字符串
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使用一个简单的字符串
类型,并在需要存储/传输ID的任何地方自行进行必要的转换。对于ID字段,您应该使用bson包提供的原语.ObjectID
"go.mongodb.org/mongo-driver/bson/primitive"
ID primitive.ObjectID `json:"_id" bson:"_id"`
什么是xid.ID
?您可以发布类型声明及其方法吗?另外,DeleteMany()
返回一个错误,不要忽略它,错误是什么?可能是您没有删除文档的权限……我忽略了错误,因为它不会返回任何错误。您还必须使用bson
标记,而不是json
。请在您的联系人
结构中将json
更改为bson
,或者如果您也使用json,也可以添加bson
。@icza更新了更多的代码看起来您使用字符串id
和Find()
,与DeleteMany()
相同吗?另外,您是否尝试过使用bson
标记?
"go.mongodb.org/mongo-driver/bson/primitive"
ID primitive.ObjectID `json:"_id" bson:"_id"`