【问题标题】:Finding a MongoDB document through a word in a field description in each product with Mongoskin使用 Mongoskin 通过每个产品中的字段描述中的一个单词来查找 MongoDB 文档
【发布时间】:2015-04-08 14:09:03
【问题描述】:

这是我的 MongoDB 中的文档示例:

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

搜索“描述”不起作用(这是我需要帮助的地方):

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);
    });
});

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

【问题讨论】:

    标签: node.js mongodb express mongoskin


    【解决方案1】:

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

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

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

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

    因此,您可以在路由实现中使用相同的方法,使用 find() 方法返回所有匹配的文档,而不是只返回一个文档的 findOne()

    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

    【讨论】:

    • 我有一个小问题。我使用了第二个选项。为什么这段代码不起作用?如果我像这样从控制台mongodb调用> db.itemData.find ({$ text: {$ search: "product"}}) 系统找到我的产品,但如果我调用搜索方法不起作用(@ 987654324@), 什么可以到期?
    • @Despotars 您可以改用查询字符串,我已更新答案以包含此内容; http://localhost/description?q=product
    • 我使用了这个:localhost:3000/description?q=coffe,我收到了这个:“响应不包含任何数据”但是,如果我在 mongo 终端中写这句话,我收到了文件。为什么会这样?
    • @Despotars 再次,我鼓励您为此提出一个新问题,因为如果我们继续针对出现的每个新问题更新答案,它会变得很麻烦。
    • 但这是同一个问题,对吧?我使用了此代码,但没有收到文档,您认为我需要针对此问题打开一个新问题吗?
    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多