I've a "words" collection in MongoDB. When I want to search the collection I want to list first words that starts with the "word" and then contains the "word" that I querid. In the same array I get this result; "simarte", "Cumartesti", "Mart", "marti", "martilar". When I search with contains it brings me other words that contains the "word" (mart).
I want to order first the words that starts with the "word" than order "contains" the words. Is it possible to do that in one query? I don't want to make a second request to db.
Here is my code sample:
var word = "mart";
db.words.find({"w" : {$regex : ".*" + word + ".*"}}, function(err, words) {
if( err || !words) console.log("No data found");
else{
res.render('index', { title: 'Words', word_data: words, word : word });
}
});
I believe it is not possible, since if you sort by w field, mongodb will consider the first letter to sort (and the second if first is equals, etc).
Maybe text search could help you. It contains a score field in results and you can sort by it. As @WiredPrairie pointed, Text Search isn't production ready, so be careful.
Another option is sort results programmatically.
Here you can find more info about that: