MongoDB textScore 按单词位置

MongoDB textScore by word position

如何在 MongoDB 中设置文本搜索,以便为关键字首先出现的结果提供更高的分数?

例如,这是我现在正在做的事情:

db.product.aggregate(
  [
    { $match: { $text: { $search: "notebook acer" }, isAvailable: true } },
    { $sort: { score: { $meta: "textScore" } } },
    { $project: { searchName: 1, _id: 0, score: { $meta: "textScore" } } }
  ]
)

我得到的结果是:

{
    "searchName" : "Mochila para Notebook Acer",
    "score" : 1.25
},
{
    "searchName" : "Notebook Acer E5-471-36me Intel Core I3 1.90ghz 4gb Hdd 500gb Linux Hdmi",
    "score" : 1.0625
}

但是我需要第二个结果在前面,因为关键字在索引字段中首先出现。

有什么办法可以实现吗?

我认为你必须使用运算符$indexOfCP,你可以用那个计算你的单词的位置,然后你可以在这个位置上排序你计算。

https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/

位置部分是这样的:

db.product.aggregate(
   [
     { $project: { kwPosition: { $indexOfCP: [ "$searchName", "notebook acer" ] } } },
     { $match: { "kwPosition": {"$ne": -1} } },
     { $sort: { kwPosition: 1 } }
   ]
)

您可以结合这两种逻辑。