【问题标题】:How do I make searches on Mongodb using wildcard characters?如何使用通配符在 Mongodb 上进行搜索?
【发布时间】:2016-03-30 14:32:23
【问题描述】:

例如,如果我的关键字是“all”,我希望 MongoDb 返回给定字段中包含单词“all”的所有文档,例如“edgar allan poe”或“whitney hall”。我如何在 MongoDb 中做到这一点?我已经被困在这里好几天了,所以任何帮助将不胜感激:)

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    通过使用正则表达式。 MongoDb 有一个$regex 运算符。

    db.authors.find({name: {$regex: 'all', $options: 'i'}});
    

    正则表达式操作不能使用索引,因此 find() 操作效率不高。索引只能用于前缀(开头)和区分大小写的匹配,如以下查询:

    db.authors.find({name: {$regex: '^a'});
    

    【讨论】:

    • 值得注意的是,这不会使用索引,所以它根本不会很好地扩展。
    • 只有当你搜索字符串的开头时,它才会使用正则表达式的索引:^test
    • 最后缺少}。它应该是db.authors.find({name: {$regex: 'all', $options: 'i'}});
    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多