Criepstar
Criepstar

Reputation: 59

MongoDB sort the query by the first field, then by the second

So I'm trying to sort my query:

await Content.find({
    $text: {$search: `\"${query}\"`},
}

It querys in the title, text and author of a document. Basically, I want to order it by the fields, so that if the searched word is in the title field it is on the first place and so on with the author and text.

Is this even possible with mongodb or do I have to do this on the Javascript side?

Upvotes: 1

Views: 326

Answers (1)

Gibbs
Gibbs

Reputation: 22974

In most search technologies, have an option called boost. If you take solr, elasticsearch there you could apply this option to assign a priority.

It is called weights in mongo.

Reference

CreateIndex takes extra object where weight of each field part of text index can be specified. Hence the score of the resulted document multiplied by this weight factor.

Upvotes: 1

Related Questions