C
C
cfmm2018-10-26 10:39:51
MongoDB
cfmm, 2018-10-26 10:39:51

MongoDB text search and correct textScore?

There is a collection (with a text index) that looks something like this:

[{id: 1, "items" : [ "milk", "bread", "fish" ]},
{id: 2, "items" : [ "milk", "milk", "milk" ]},
{id: 3, "items" : [ "cheese", "salt" ]},
{id: 4, "items" : [ "fish", "bread"]}]

We need to find all documents that have at least one element in the items array that contains the words "milk", "bread", and "fish". And sort the result, but not by the total number of occurrences of any search words (as the code below does), but by the number of simultaneous occurrences of the search words.
coll.find({$text:{"$search": "milk bread fish"}}, {score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}})

This code sorts the result like this:
[{id: 2, "items" : [ "milk", "milk", "milk" ], "score": 3.3},
{id: 1, "items" : [ "milk ", "bread", "fish" ], "score": 3.3},
{id: 4, "items" : [ "fish", "bread"], "score": 2.2}]
And I need:
[{ id: 1, "items" : [ "milk", "bread", "fish" ], "score" : 3},
{id: 4, "items" : [ "fish", "bread"], "score ": 2},
{id: 2, "items" : [ "milk", "milk", "milk" ], "score": 1}]

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question