英文:
Golang MongoDB delete multiple items in one query
问题
我在我的数据库中有一个match
表,我需要从中删除多个项目,我想知道是否有一种方法可以使用单个查询来完成这个操作。
我在我的Go代码中获取了一个类型为[]primitive.ObjectID
的deleteList
。deleteList
基本上是一个需要删除的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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论