Sort results by search query similarity

I have this collection of users:

{ "_id" : ObjectId("501faa18a34feb05890004f2"), "username" : "joanarocha", } { "_id" : ObjectId("501faa19a34feb05890005d3"), "username" : "cristianarodrigues", } { "_id" : ObjectId("501faa19a34feb05890006d8"), "username" : "anarocha", } 

When I request this: db.users.find({'username': /anaro/i}) results are sorted in natural order (insertion order).

I would like to sort them in a similar search order. In this case, the results should be returned in the following order:

 { "_id" : ObjectId("501faa19a34feb05890006d8"), "username" : "anarocha", } { "_id" : ObjectId("501faa18a34feb05890004f2"), "username" : "joanarocha", } { "_id" : ObjectId("501faa19a34feb05890005d3"), "username" : "cristianarodrigues", } 
+4
source share
1 answer

Unfortunately, MongoDB does not support a full-text search ranking by default.

First of all, you will need an algorithm for calculating the similarity between the lines. See the following links:

Scripting similarity algorithms?

Line similarity → Levenshtein distance

Then you need to write a javascript function using an algorithm to compare two strings to pass it to your request. See the following link to find out how to achieve this:

Mongo comprehensive sorting?

+2
source

All Articles