0 votes
in MongoDB by
Can I sort with a user-defined function; e.g., supposing a and b are integers, by the difference between a and b (a-b) in MongoDB?

1 Answer

0 votes
by

I don’t think this is possible directly; the sort documentation certainly doesn’t mention any way to provide a custom compare function.

You’re probably best off doing the sort in the client, but if you’re really determined to do it on the server you might be able to use db.eval() to arrange to run the sort on the server (if your client supports it).

Server-side sort:

db.eval(function() {

return db.scratch.find().toArray().sort(function(doc1, doc2) {

return doc1.a – doc2.a

})

});

 

Versus the equivalent client-side sort:

db.scratch.find().toArray().sort(function(doc1, doc2) {

return doc1.a – doc2.b

});

Note that it’s also possible to sort via an aggregation pipeline and by the $orderby operator (i.e. in addition to .sort()) however neither of these ways lets you provide a custom sort function either. Why don’t create the field with this operation and sort on it  in MongoDB?

Related questions

0 votes
asked Oct 4, 2023 in JavaScript by DavidAnderson
0 votes
asked May 21, 2019 in Mathematics by sheetalkhandelwal
...