Mongodb: How to order a "select in" in same order as elements of the array

I'm performing this mongo query:

db.mytable.find({id:{$in:["1","2", "3", "4" ]}});

It returns all results in a strange order, as it follows:

4,3,2,1

I need to retrieve all results in same order as it was defined in the query array.

1,2,3,4

Is it possible ?

you can write a query like this :

db.mytable.find({id:{$in:["1","2", "3", "4" ]}}).sort({id:1})

To have your results ORDER BY id ASC

Source : MongoDB Advanced Queries

But if you just want to order the results based on your $in array, try to sort your $in array in the reverse order, the result regarding to the first element of your $in array is likely to appear as the last element of the results

A couple of things to note:

1.) MongoDB, like most databases, makes no guarantees about the order of results returned from your query unless you use a call to sort(). If you really want to guarantee that your query result is returned in a a specific order, you'll need to specify that specific sort order.

2.) In general, the most recently updated/moved document will show up at the end of your result set but there are still no guarantees. MongoDB uses "natural order" for its native ordering of objects and although this is very close to the order of insertion, it is not guaranteed to be the same.

3.) Indexed fields will behave differently. It's worth pointing out that it looks like your query is using id and not _id. The former, _id would be indexed by default and id would not be indexed unless you've explicitly added an index to that field.

You can read more about MongoDB's sorting and ordering here: http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order