Mongodb - 如何将聚合文本搜索与查找查询结合使用

Mongodb - how to use an aggregate text search with a find query

我在 Mongodb 中使用聚合方法进行文本搜索。我已经尝试了各种方法,但仍然找不到过滤结果的正确方法。我已经设置了一个索引,它仅适用于 $text 搜索并且仅适用于查询。

这是我执行文本搜索的代码:

Model.aggregate([
    { $match: { $text: { $search: searchValue } } },
    { $project: { displayTitle: 1, title: 1, body: 1, _type: 1, _id: 1, score: { $meta: "textScore" } } },
    { $match: { score: { $gt: 1.0 } } }
], function (err, models) {

})

但是我希望能够通过此查询进一步过滤模型:

Model.find({_parentIds: {$in: arrayOfIds}})

我原以为这会起作用:

Model.aggregate([
    { $match: { $text: { $search: searchValue }, _parentIds: {$in: arrayOfIds} } },
    { $project: { displayTitle: 1, title: 1, body: 1, _type: 1, _id: 1, score: { $meta: "textScore" } } },
    { $match: { score: { $gt: 1.0 } } }
])

但遗憾的是它没有。有人试过这个还是我遗漏了什么?

这是我正在搜索的示例集合:

[{
    displayTitle: "first item",
    title: "first_item",
    _type: "item",
    _parentIds: ["123", "234"]
}, {
    displayTitle: "second item",
    title: "second_item",
    _type: "item",
    _parentIds: ["123", "234"]
}, {
    displayTitle: "third item",
    title: "third_item",
    _type: "item",
    _parentIds: ["345", "456"]
}]

我当前的搜索是这样的:

searchValue = "item"
arrayOfIds = ["345"];

并且只希望返回此文档:

{
    displayTitle: "third item",
    title: "third_item",
    _type: "item",
    _parentIds: ["345", "456"]
}

谢谢!

文字得分为0.75。因此,将匹配过滤器更改为大于 0.5 即可。

修改投影以排除正文、_id 并包括父 ID。

使用此查询创建索引。

db.textcol.createIndex( { displayTitle: "text" } )

运行 这个查询。

db.textcol.aggregate([
    { $match: { $text: { $search: "item" }, _parentIds: {$in: ["345"]} }} ,
    { $project: { displayTitle: 1, title: 1, _type: 1, _id: 0, _parentIds :1, score: { $meta: "textScore" } }},
        { $match: { score: { $gt: 0.5 } } }
])

输出:

{
    "displayTitle": "third item",
    "title": "third_item",
    "_type": "item",
    "_parentIds": ["345", "456"],
    "score": 0.75
}