365Tools
    发布时间:2024-03-30 20:30:01
在编程语言中,正则表达式可以使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。MongoDB 可以使用 $regex 操作符来设置匹配字符串的正则表达式,MongoDB 使用 PCRE(Perl 兼容的正则表达式)作为正则表达式语言。
> db.posts.insert(
... {
...    "post_text": "enjoy the mongodb articles on bianchengbang",
...    "tags": ["mongodb", "bianchengbang"]
... }
... )
> db.posts.find({post_text:{$regex:"bianchengbang"}}).pretty()
{
        "_id" : ObjectId("6041dfc3835e4aa734b591df"),
        "post_text" : "enjoy the mongodb articles on bianchengbang",
        "tags" : [
                "mongodb",
                "bianchengbang"
        ]
}
上面的查询也可以写成如下所示的样子:
> db.posts.find({post_text:/bianchengbang/}).pretty()
{
        "_id" : ObjectId("6041dfc3835e4aa734b591df"),
        "post_text" : "enjoy the mongodb articles on bianchengbang",
        "tags" : [
                "mongodb",
                "bianchengbang"
        ]
}
> db.posts.find({post_text:{$regex:"BianChengBang",$options:"$i"}}).pretty()
{
        "_id" : ObjectId("6041dfc3835e4aa734b591df"),
        "post_text" : "enjoy the mongodb articles on bianchengbang",
        "tags" : [
                "mongodb",
                "bianchengbang"
        ]
}
> db.posts.find({tags:{$regex:"b"}}).pretty()
{
        "_id" : ObjectId("6041dfc3835e4aa734b591df"),
        "post_text" : "enjoy the mongodb articles on bianchengbang",
        "tags" : [
                "mongodb",
                "bianchengbang"
        ]
}