使用 Mongoskin 通过每个产品的字段描述中的单词查找 MongoDB 文档

Finding a MongoDB document through a word in a field description in each product with Mongoskin

这是我 MongoDB:

中的文档示例
{
    "_id": ObjectId('5525039895884d66710d0fc3'),
    "prid": "63527",
    "data": {
        "sku": "HF22-81639",
        "name": "Product Test",
        "ean": "8763900872512",
        "description": "This product is my first test",
    }
}

搜索 "description" 无效(这是我需要帮助的地方):

app.get("/description/:id", auth, function(req, res, next) {
    req.collection.findOne({
        "data.description": req.params.id
    }, function(e, result) {
        if(e) return next(e);
        res.send(result);
    });
});

我需要通过一个词来查找,集合中存在的所有产品的描述字段中都包含该词。

要通过一个词查找,集合中存在的所有产品都在描述字段中包含该词,您需要一个不区分大小写的正则表达式匹配。您可以使用以下查询(作为示例):

db.product.find({"data.description": /test/i});

其中 /test/i 中的 i 表示不区分大小写,因此正则表达式匹配任何包含字符串 "test" 的文本的描述字段。等效的 SQL 表达式如下:

select * from product where description like '%test%'

因此您可以在路由实现中使用相同的方法,使用 find() method to return all matched documents instead of the findOne() 其中 returns 只有一个文档:

app.get("/description/:id", auth, function(req, res, next) {
    req.collection.find({
        "data.description": /req.params.id/i
    }, function(e, result) {
        if(e) return next(e);
        res.send(result);
    });
});

另一种选择是在查找操作中使用 $text 运算符,因为它对使用文本索引索引的字段的内容执行文本搜索。所以你要做的第一件事是在描述字段上创建一个文本索引:

db.collection.createIndex( { "data.description": "text" } )

之后您可以使用 $text 运算符进行查询。例如,以下查询搜索术语咖啡:

db.collection.find( { $text: { $search: "coffee" } } )

编辑:

在所有条件都相同的情况下,您可以更新路由实现以使用 URL 中的查询字符串来代替:

app.get("/description", auth, function(req, res, next) {
    req.collection.find({
        $text: { $search: req.params.q }
    }, function(e, result) {
        if(e) return next(e);
        res.send(result);
    });
});

您可以在浏览器中查询 http://localhost/description?q=product