Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang MongoDB delete multiple items in one query

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading