I was wondering if there was a way to sort my mongodb results by the index of the search keyword.
For example if I search the db by {name: da}
i'll get back results like [{name: "yoda"}, {name: "david"}, {name: "soda"}, {name: "daniel"}]
. But I would want the order to be something like this [{name: "david"}, {name: "daniel"}, {name: "yoda"}, {name: "soda"}]
. I know that I can sort the results after I find them like this:
const re = new RegExp(keyword, "i");
results.sort((a, b) => a.name.search(re) - b.name.search(re)
But I also wanted to limit the amount of documents I get back from the database. I looked at the textScore metadata in the mongodb docs, but I have no clue if its useful in my case.
Copyright Notice:Content Author:「dahveed」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/68697479/sort-by-keyword-index-mongodb