Joe
Joe2y ago

order by

What's the best way to do an order by query? I saw there's .order() and orderedQuery, but I wasn't sure for .order() if I can pick the field that works on? Thanks!
2 Replies
lee
lee2y ago
hi! the way to order by custom fields is to define an index (https://docs.convex.dev/database/indexes/). a query like db.query('scores').withIndex('by_score') will return documents in the table sorted by score. it's ascending by default and you can use .order('desc') to reverse the order. if you're not worried about performance (you don't have many documents) and don't want to define an index, then you could instead fetch documents and then sort in javascript, like
const scores = await db.query('scores').collect();
scores.sort((a, b) => a.score - b.score);
const scores = await db.query('scores').collect();
scores.sort((a, b) => a.score - b.score);
Joe
JoeOP2y ago
thanks!

Did you find this page helpful?