Reputation: 5907
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
Reputation: 9473
such approach could be done using aggreagtion framework
stages will be:
Match - select elements matching regex
Group elements by expression if starts with regex phrase -> true, else false
sort by expression from 2
What do you think?
Upvotes: 1