Passing a field value to the sort method via a function parameter

I am trying to pass a field to the sort method via a parameter but it is not working.

var sortBy = “deliveryDate”
db.orders.aggregate([{$match:{}}, {$sort: {sortBy: -1}}, {$limit: 10}])

Note: sortBy can either be orderDate or deliveryDate.

What an I doing wrong?

Hello @Chris_Job1, Welcome back to the MongoDB community forum,

I can see you have assigned the value in sortBy variable but not used it in the aggregation query, you have written the property name statically { sortBy: -1 }, and that will not refer to the variable,

You can try this, wrapping property name in array blocks [sortBy],

var sortBy = “deliveryDate”
db.orders.aggregate([{$match:{}}, {$sort: {[sortBy]: -1}}, {$limit: 10}])

That’s what I missed!!
Thank you!!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.