首页 文章

检查查询是否包含文档字段中的字符串

提问于
浏览
2

有没有办法检查文档字段是否包含查询中的字符串?

例如:

集合 cities

{ "_id" : 1, "name" : "Madrid" }
{ "_id" : 2, "name" : "Lisbon" }
{ "_id" : 3, "name" : "Paris" }

查询:

db.cities.find({
    name: {$isIn: 'Address of the street, Lisbon'}
});

结果:

{ "_id" : 2, "name" : "Lisbon" }

2 回答

  • 3

    是的,这是可能的 . 看看$text documentation . 基本上你必须在字段上创建一个文本索引,然后你可以搜索如下:

    db.cities.find({ $text: { $search: "Address of the street, Lisbon" } })
    

    在这种情况下创建索引的示例 . 由于您的字段名为 name

    db.cities.createIndex( { name: "text" } )
    

    您有许多可能性,例如排除短语,仅包含,区分大小写等 .

    所以我要说我添加以下文件:

    { "_id" : NumberInt(1), "name" : "Madrid" }
    { "_id" : NumberInt(2), "name" : "Lisbon" }
    { "_id" : NumberInt(3), "name" : "Paris" }
    { "_id" : NumberInt(4), "name" : "Address"}
    

    如果我们这样搜索:

    db.cities.find({ $text: { $search: "Address of the street, Lisbon" } })
    

    我们会得到2个结果:

    { "_id" : NumberInt(2), "name" : "Lisbon"}
    { "_id" : NumberInt(4), "name" : "Address"}
    

    但是,如果我们这样搜索:

    db.cities.find({ $text: { $search: "-Address of the street, Lisbon" } })
    

    我们只会得到:

    { "_id" : NumberInt(2), "name" : "Lisbon"}
    

    因为使用( - )您可以排除包含此术语的文档 . 有关更多可能性,请查看文档

  • 2
    db.cities.find({"name" : {$regex : ".*Lisbon.*"}});
    

    是的,你可以使用正则表达式来找到一些字符串模式 .

相关问题