代码之家  ›  专栏  ›  技术社区  ›  Gary Richardson

MongoDB Regex整数值搜索

  •  16
  • Gary Richardson  · 技术社区  · 14 年前

    我想在mongodb中搜索整数值。这可能吗?

    我正在构建一个CRUD类型的接口,它允许*在各个字段上使用通配符。我正试图使一些字段的UI保持一致,这些字段是整数。

    考虑:

    > db.seDemo.insert({ "example" : 1234 });
    > db.seDemo.find({ "example" : 1234 });
    { "_id" : ObjectId("4bfc2bfea2004adae015220a"), "example" : 1234 }
    > db.seDemo.find({ "example" : /^123.*/ });
    > 
    

    如您所见,我插入了一个对象,并且能够通过值找到它。如果我尝试一个简单的regex,我实际上找不到对象。

    谢谢!

    2 回复  |  直到 8 年前
        1
  •  39
  •   dalton    14 年前

    如果您想对数字进行模式匹配,那么在mongo中进行匹配的方法是使用$where表达式并传入模式匹配。

    > db.test.find({ $where: "/^123.*/.test(this.example)" })
    { "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }
    
        2
  •  4
  •   Sede    8 年前

    我不太喜欢使用 $where 查询运算符,因为它评估查询表达式的方式以及查询使用用户输入数据时的安全风险。

    也就是说,最好的办法是 $project 您的文档并添加另一个计算字段,该字段是您的数字的字符串值。

    这个 $toLower 他的兄弟姐妹 $toUpper 运算符分别将字符串转换为小写和大写,但有一点未知的特性,即可以使用它们将整数转换为字符串。

    这个 $match 运算符返回所有与模式匹配的文档,使用 $regex 操作员。

    db.seDemo.aggregate(
        [ 
            { "$project": { 
                "stringifyExample": { "$toLower": "$example" }, 
                "example": 1 
            }}, 
            { "$match": { "stringifyExample": /^123.*/ } }
        ]
    )
    

    收益率:

    { 
        "_id" : ObjectId("579c668c1c52188b56a235b7"), 
        "example" : 1234,
        "stringifyExample" : "1234"
    }
    
    { 
        "_id" : ObjectId("579c66971c52188b56a235b9"), 
        "example" : 12334,
        "stringifyExample" : "12334"
    }
    

    现在,如果您想要的是检索包含特定子字符串的所有文档,那么更简单、更好的方法是在即将发布的MongoDB(本文撰写时)中使用 $redact 允许 $cond 逻辑处理。 $indexOfCP .

    db.seDemo.aggregate([ 
        { "$redact": { 
            "$cond": [ 
                { "$gt": [ 
                    { "$indexOfCP": [ 
                        { "$toLower": "$example" }, 
                        "123" 
                    ] }, 
                    -1 
                ] }, 
                "$$KEEP", 
                "$$PRUNE" 
            ] 
        }}
    ])
    

    产生:

    { 
        "_id" : ObjectId("579c668c1c52188b56a235b7"), 
        "example" : 1234 
    }
    
    { 
        "_id" : ObjectId("579c66971c52188b56a235b9"), 
        "example" : 12334 
    }