1

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?

davnicwil
  • 28,487
  • 16
  • 107
  • 123
hpkancha
  • 96
  • 3
  • The basic concept even though I am not familiar with the syntax in this library is using the **`$in`** operator with a list. So if you can somehow "map" out all your `_id` values into a list type then you should be able to send as an argument using that operator. I see there is a section on "Query Templating" under the [Query](http://jongo.org/#querying) examples on the main site that might apply to this. – Neil Lunn Jun 05 '14 at 07:20
  • Thanks Neil, that helped a lot with the deletes. With updates though, I am able to extract out all the documents that need to be updated, but I am still not sure how to save all the new documents in one go. The with() and save() methods of Jongo accept only 1 Object at a time and do not accept a collection of Objects – hpkancha Jun 05 '14 at 21:59
  • As I have said before I don't really have any experience with Jongo and also a lack of time to try out some examples, but if you have a MongoDB 2.6 or greater version then this manual section on [Bulk Update](http://docs.mongodb.org/manual/reference/command/update/#bulk-update) may be of interest. I have posted a few answers on the usage, and there should be a way for you to at least get to the raw database object from the Java driver in order to use the required `runCommand` version of this. Or possibly other bulk update API exposed by your Java driver if it is a recent release. – Neil Lunn Jun 05 '14 at 23:45

1 Answers1

2

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" });
davnicwil
  • 28,487
  • 16
  • 107
  • 123