Home > Mobile >  Golang MongoDB delete multiple items in one query
Golang MongoDB delete multiple items in one query

Time:09-27

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.

CodePudding user response:

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
}
  • Related