Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: sort documents by array of ids

Say you have an array of document ids stored elsewhere (e.g. in Redis sorted set).

What is the most efficient way of querying Mongo documents with { _id: { $in: ids }} and having the results sorted in the same ordering as it was in ids array?

Example

var ids = [3,2,1,6,7];

db.records.find({ _id: { $in: ids }})
 .sort({ 
   // ???
 });

// expecting [{_id: 3}, {_id: 2}, {_id: 1}, {_id: 6}, {_id: 7}]

P.S. I know I can do the sorting in application, but I wonder, if it could be done with more efficiency at the backend.

like image 235
BorisOkunskiy Avatar asked Dec 04 '13 12:12

BorisOkunskiy


People also ask

How do I sort an array element in MongoDB?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

How do I sort a list in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Where is MongoDB ID list?

MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.

How do I sort groups in MongoDB?

And for group sorting in MongoDB, the $group operator is used with the $sort operator. With the help of the $group and $sort operator, MongoDB can also sort the grouped data in ascending or descending order. In this post, we have provided an informative insight into the aggregate group sort functionality of MongoDB.


1 Answers

You cannot do it in MongoDB right now. There is an open issue in jira.

SERVER-7528

like image 154
Parvin Gasimzade Avatar answered Sep 17 '22 12:09

Parvin Gasimzade