Sample collection "test", (with text index on field1, field2, field3) :
/* Item 1 */
{
"_id" : ObjectId("6011862888de9cd2347828e6"),
"field1" : "Denver Segment1",
"field2" : "student1 zero1",
"field3" : "cat2 dog0"
}
/* Item 2 */
{
"_id" : ObjectId("6011866b88de9cd234782906"),
"field1" : "meow cap",
"field2" : "teacher eleven1",
"field3" : "cat2 cow"
}
/* Item 3 */
{
"_id" : ObjectId("6011868b88de9cd234782909"),
"field1" : "bark cake",
"field2" : "admin hey",
"field3" : "bird chirp"
}
And I am trying to sort the records based on number of keywords matched.
I have the following query (keywords are cat2 and student1)
db.getCollection('test').find(
{ $text: { $search: "cat2 student1" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
The result is the following:
/* 1 */
{
"_id" : ObjectId("6011862888de9cd2347828e6"),
"field1" : "Denver Segment1",
"field2" : "student1 zero1",
"field3" : "cat2 dog0",
"score" : 1.5
}
/* 2 */
{
"_id" : ObjectId("6011866b88de9cd234782906"),
"field1" : "meow cap",
"field2" : "teacher eleven1",
"field3" : "cat2 cow",
"score" : 0.75
}
This is fine, but I do not how to get the actually keywords shown as well.
For example expected result should be the following:
/* 1 */
{
"_id" : ObjectId("6011862888de9cd2347828e6"),
"field1" : "Denver Segment1",
"field2" : "student1 zero1",
"field3" : "cat2 dog0",
"score" : 1.5,
"matched-keywords":["cat2","student1"]
}
/* 2 */
{
"_id" : ObjectId("6011866b88de9cd234782906"),
"field1" : "meow cap",
"field2" : "teacher eleven1",
"field3" : "cat2 cow",
"score" : 0.75,
"matched-keywords":["cat2"]
}
```
How can I do this ?
question from:
https://stackoverflow.com/questions/65922538/finding-the-number-of-matched-keywords-in-text-index-in-mongodb