tags:

views:

22

answers:

1

The MongoDB docs on the $in conditional operator don't say anything about order. If I run a query of the form

db.things.find({'_id': {'$in': id_array}});

what will be the order of the returned results? And is there a way for me to tell MongoDB "I want the results sorted so that they're in the same order as the ids in id_array?"

+1  A: 

the order of the results isn't mentioned because they won't be ordered in any dependable way. the only way to get them ordered would be to do separate queries client-side for each item in the $in array

mdirolf
OK, that's what I expected. So let's say I'm making the query via PyMongo. Then I can either:1. Make a separate MongoDB for each id in id_array and append it to the end of a list (inefficient because of the excess queries), or2. Make the single MongoDB query given in my question, then use Python to copy the results from MongoDB into a properly ordered list (inefficient because I'm copying potentially large amounts of data on the client side)?There isn't a better way? Some kind of custom query I can run on MongoDB that will sort the results before they're returned?
Trevor Burnham
you could change your schema. there is actually a question going on the mongodb-user list right now discussing exactly that option, for exactly this question. should probably just check that out and follow up there.
mdirolf