Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 556
larrytron Avatar asked Oct 02 '12 15:10

larrytron


2 Answers

There is indeed no guarantee about the order of results returned from your query, but you could do a sort afterwards with the result. Two examples, the first one with the order you wanted, the second one reversed.

const arr = ["1", "2", "3", "4" ];

db.collection.find({ id: { $in: arr }})  
  .then(result => {
    
    let sorted = arr.map(i => result.find(j => j.id === i));
    console.log(sorted) // 1, 2, 3, 4

    let reversed = arr.reverse().map(i => result.find(j => j.id === i));
    console.log(reversed) // 4, 3, 2, 1
    
});

In case you want to do real MongoDB ID lookups, use db.collection.find({ _id: { $in: arr }}) and .map(i => result.find(j => j._id == i)) (Notice the two equal signs instead of three)

like image 50
Kurt Van den Branden Avatar answered Oct 14 '22 09:10

Kurt Van den Branden


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

like image 27
Brandon Black Avatar answered Oct 14 '22 09:10

Brandon Black