yyunikov
yyunikov

Reputation: 5907

MongoDb: sort text search results

I've created a query which returns results that contain "Be" inside the field value. e.g.:

db.collection.find({ "$or" : [ { "name.en" : { "$regex" : "Be" } } , { "defaultName" : { "$regex" : "Be" } } ] })

However, the returned results are sorted in random way, some contain "Be" inside the word, some in the beginning, some in the end.

Is it possible to create a single query which would sort results the following way: first returned results will start with "Be" and then will be all the rest?

Query results example:

{
"defaultName" : "Belgium",
...
},
{
"defaultName" : "Berlin",
...
},
{
"defaultName" : "Bombei",
...
},
{
"defaultName" : "Danube",
...
}

Upvotes: 2

Views: 72

Answers (1)

profesor79
profesor79

Reputation: 9473

such approach could be done using aggreagtion framework

stages will be:

  1. Match - select elements matching regex

  2. Group elements by expression if starts with regex phrase -> true, else false

  3. sort by expression from 2

What do you think?

Upvotes: 1

Related Questions