【问题标题】:MongoDB regex string startswith and endswith [duplicate]MongoDB正则表达式字符串以开头和结尾[重复]
【发布时间】:2018-11-25 16:27:33
【问题描述】:

所以我有一些看起来像这样的东西

db.usuarios.insert
(
    [
        {
            "nome" : "neymala",
            "idade" : 40,
            "status" : "solteira"
        },
        {
            "nome" : "gabriel",
            "idade" : 31,
            "status" : "casado"
        },
        {
            "nome" : "jose",
            "idade" : 25,
            "status" : "solteiro"
        },
        {
            "nome" : "manoel",
            "idade" : 25,
            "status" : "solteiro",
            "interesses" : [
                "esporte",
                "musica"
            ]
        }
    ]
)

我想查找以 ma 开头并以 l 结尾的名称,例如“manoel”或“manuel”

我已经想出了如何处理闲置查询:

db.usuarios.find({nome:{$regex: /^ma/ }})

db.usuarios.find({nome:{$regex: /l$/ }})

现在我想将它们组合成一个查询。

【问题讨论】:

标签: json regex mongodb


【解决方案1】:

您可以将这两个要求组合成一个正则表达式:

db.usuarios.find({nome: /^ma.*l$/})

在正则表达式中,.* 表示匹配 0 个或多个任意字符。所以这个正则表达式匹配以ma 开头并以l 结尾的名称,忽略两者之间的任何内容。

【讨论】:

    【解决方案2】:

    将两个查询与 AND 运算符结合起来

    db.usuarios.find({
    $and:[
        {nome:{$regex: /^ma/ }},
        {nome:{$regex: /l$/ }}
    ]
    
    })
    

    【讨论】:

    • 答案是对的,但是$regex这里没有必要。 {nome: /^ma/} 很好。
    【解决方案3】:

    在 javascript 中,/.../ 是一个正则表达式,因此不需要 $regex

    db.usuarios.find({
        $and:[
            {nome: /^ma/ },
            {nome: /l$/ }
        ]
    })
    

    还要注意starts with 可以命中索引。 ends with 不能。这样你最好有一个选择性的starts with,否则会有大量的对象扫描可能会占用额外的 CPU 并可能减慢你的查询速度。

    【讨论】:

    • 提高endswith 性能的一种解决方法是在文档中插入该字段的副本,但内容颠倒。
    【解决方案4】:

    也许这段代码对你有帮助。

    可以搜索小写字母串和大写字母串......

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 2017-09-17
      • 2015-04-27
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2019-07-20
      相关资源
      最近更新 更多