Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of responses to MongoDB $in query? [duplicate]

Tags:

mongodb

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?"

like image 589
Trevor Burnham Avatar asked Jun 29 '10 15:06

Trevor Burnham


1 Answers

Asked for this feature on JIRA:

Quickly got a pretty good response: use $or instead of $in

c.find( { _id:{ $in:[ 1, 2, 0 ] } } ).toArray() 

vs.

c.find( { $or:[ { _id:1 }, { _id:2 }, { _id:0 } ] } ).toArray() 

Read the bug report for more info.

Update:

The $or work-around hack no longer works starting with 2.6.x - it was a side effect of implementation which has changed.

like image 71
Jonathan Ong Avatar answered Sep 17 '22 10:09

Jonathan Ong