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?
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.
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.
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.
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.
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.
You cannot do it in MongoDB right now. There is an open issue in jira.
SERVER-7528
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With