Golang MongoDB delete multiple items in one query

huangapple go评论92阅读模式
英文:

Golang MongoDB delete multiple items in one query

问题

我在我的数据库中有一个match表,我需要从中删除多个项目,我想知道是否有一种方法可以使用单个查询来完成这个操作。
我在我的Go代码中获取了一个类型为[]primitive.ObjectIDdeleteListdeleteList基本上是一个需要删除的match.id列表。我可以轻松地遍历我的deleteList切片,并逐个删除所有的matches,但我觉得应该有一种更高效的方法来使用一个查询来完成,而不是用多个查询来淹没我的数据库。

有人知道可能的解决方案吗?

谢谢。

英文:

I have a match table in my DB and I need to delete multiple items from it and I was wondering if there is a way to do this using a single query.
I get deleteList of type []primitive.ObjectID in my Go code. deleteList is basically a list of match.id that need to be deleted. I could easily do it ranging through my slice of deleteList and deleting all the matches 1 by 1, but I feel like there should be a more efficient way of doing it in one query instead of flooding my db with multiple queries.

Does anyone know a possible solution for this?

Thank you.

答案1

得分: 2

你可以使用Collection.DeleteMany()方法。

构建一个匹配你的任何ID的过滤器,并将其传递给DeleteMany()方法,如下所示:

c := ...                      // 获取匹配的集合
ids := []primitive.ObjectID{} // 要删除的ID列表

filter := bson.M{"_id": bson.M{"$in": ids}}

if _, err := c.DeleteMany(ctx, filter); err != nil {
    // 处理错误
}
英文:

You may use Collection.DeleteMany().

Construct a filter that matches any of your IDs, and pass that to DeleteMany() like this:

c := ...                      // acquire match collection
ids := []primitive.ObjectID{} // the id list to delete

filter := bson.M{"_id": bson.M{"$in": ids}}

if _, err := c.DeleteMany(ctx, filter); err != nil {
    // handle error
}

huangapple
  • 本文由 发表于 2022年9月27日 17:07:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73865004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定