Nic Cottrell
Nic Cottrell

Reputation: 9685

Best way to load multiple objects by ObjectId in order in a single query?

I have a list of ObjectIDs for some objects I want to load from MongoDB. Currently I loop through each and do a get using the Java driver, but this is very inefficient.

I tried the Morphia Datastore.get(java.lang.Class<T> tClass, java.lang.Iterable<V> vs) method and passed it a list of IDs. Unfortunately the order is not preserved, I guess because it's using the $in: {...} syntax.

Is there a way to do a single query and get the objects in an arbitrary order?

Update: to be clear, I have an ordered list of IDs and want to load the corresponding objects in the same order.

Upvotes: 2

Views: 574

Answers (3)

Sridhar Nanjundeswaran
Sridhar Nanjundeswaran

Reputation: 754

Maybe I am not understanding your question here. Is there a reason you are not doing the $in query from the driver directly with the sort option? Does the following code not work for you?

ArrayList ids = new ArrayList();
ids.add(new ObjectId("51e9cc5496674e6b7bcea11f"));
ids.add(new ObjectId("51e9cc5296674e6b7bcea11e"));
BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$in", ids));
BasicDBObject sort = new BasicDBObject("_id", -1);
DBCursor cursor = coll.find(query).sort(sort);

Upvotes: 0

Sebastien Lorber
Sebastien Lorber

Reputation: 92180

As far as I know, there is not such an option, and we don't even need such an option.

What I've done recently using Mongo is to create a findByIds(Iterable<ObjectId> ids) which will do mostly what Morphia seems to do, except it will return the result as a Map<ObjectId,Model> (or Map<String,Model>)

There were different possible strategies to handle ids that couldn't be found:

  • Do not put the key in the map (which I choose)
  • Put the key with a null value
  • Raise an exception

And I iterated over the Iterable so that I'm sure it preserves the iteration order (using a LinkedHashMap)

You could do something similar. You have everything you need to sort the MongoDB result in your iteration order. Everything is already in memory, it doesn't cost so much...

Upvotes: 1

David Hofmann
David Hofmann

Reputation: 5775

You can reorder them after getting them from the database.

Upvotes: 1

Related Questions