0

I'm building an application in node/express, using mongoose and mongodb for data.

I have a "games" collection in mongo that has tens of thousands of games.

Each game has a "title", and I would like to be able to search for a title (e.g. halo 2) and have the results display in a user friendly order.

Halo 2 should come before Halo 5, and irrelevant results should not be included.

Also, insane results should be excluded: e.g. query for "halo combat evolved" should not return "Evolve" as the highest scored result.

Ultimately, I'll be querying this from mongoose in my node app, but for the process of prototyping I've just been using the mongo console...

Here is a sample of what I've tried (which ultimately failed):

db.games.find(
    {$text: {$search: "halo combat evolved"}},
    {score: {$meta: "textScore"}}
)

And here is a print screen of the results, sorted by score:

Bad results

flexage
  • 457
  • 1
  • 9
  • 19

1 Answers1

1

First of all, you must define a "text" index referring to your text property. This is in order to improve the speed of the query.

db.games.ensureIndex({title: 'text'})

this will create an index for the title property of your games collection, however, you must be aware that this could take a long time if your collection is really big.

Once you have created the index, now you can query the collection as follows

db.games.find(     
    {$text: {$search: "halo combat evolved"}},
    {score: {$meta: "textScore"}}
).sort( { score: { $meta: "textScore" } } )

as you can see, I'm using the sort method in order to sort the results according the relevance which is just a percent of coincidence with your query.

There are some other configurations that you could use when searching text on mongo, here is a good resource information about it mongo text index

Roger
  • 579
  • 4
  • 13