简体   繁体   中英

how to add special characters in mongo $regex

I want to look for "\\r" in a string field I have in mongo, and I fount this, which looks like it works good:

db.users.findOne({"username" : {$regex : ".*son.*"}});

the problem is that i want to look for "\\r" and I can find it, which I know its there, so I just did:

db.users.findOne({"username" : {$regex : ".*\r.*"}});

and it dosent work, how can I fix this?

example document:

{
    "personId" : 1,
    "personName" : "john",
    "address" : {
        "city" : "Rue Neuve 2\\r\\rue Pré-du-Mar \\r ché 1 1003 Lausanne",
        "street" : "",
        "zipCode" : "",
        "streetNumber" : ""
    }
}

so my query is:

db.users.findOne({"address.city" : {$regex : ".*\r.*"}});

also tried:

db.users.findOne({"address.city" : {$regex : ".*\\r.*"}});

尝试

db.users.findOne({"username" : {$regex : ".*\\r.*"}});

I think your issue is that you have your .* backwards at the end. You are looking for a "2." literal followed by any characters as opposed to what you have at the beginning, .*, saying anything before the literal that isn't a carriage return. Try to change this to

db.users.findOne({"username" : {$regex : ".*\\r*."}});

Which says give me "\\r" with any non carriage return characters before the literal and any non carriage return characters after the literal.

我发现做到这一点的方法是:

db.users.findOne({"username" : {$regex : ".*\\\\.*"}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM