Update / delete multiple objects using Jongo

2.2k Views Asked by At

I have a method which takes in a Collection of Objects that are to be deleted.

This is the way I am deleting them now

public void deleteAll(Collection<Object> objs){
     for(Object obj : objs) {
       collection.remove("{ _id: # }", obj.getId());
     }
}

I am doing something very similar for update where I am looping through the passed collection of Objects. This seems to be very time consuming.

Is there a better way of doing the update/delete?

1

There are 1 best solutions below

0
On

It's possible to both remove and update multiple documents with a single query.

remove

You need to use a query with a selector using $in, and an array of _id values to match.

With Jongo, you can build the list to match with $in into the query in a couple of different ways

// pass an array of ids
ObjectId[] ids = {id1, id2, id3};
collection.remove("{ _id: { $in: # } }", ids);

// or pass each id separately
collection.remove("{ _id: { $in:[#, #, #] }}", id1, id2, id3);

update

Exact same concept as above using $in to select the objects you want to update, however you also have to set the multi option, so that the update applies to all the documents it matches against, not just the first.

With Jongo this is done like so

ObjectId[] ids = {id1, id2, id3};
collection
  .update("{ _id: { $in: # } }", ids)
  .multi()
  .with({ $set: { foo: "bar" });