简体   繁体   中英

Mongodb string match regex

I have a few mongodb docs like below:

{
    ...
    ipAddress: "1.2.3.4"
},
{
    ...
    ipAddress: "1.2.3.44,1.2.5.7"
}

The ipAddress is a string field that can contain many IPs that are separated by comma. ( "1.2.3.4,1.3.5.7,2.4.6.8" etc)

I would like to retrieve a mongo document that matches a particular IP. For which, I try the below query:

collection.findOne({
    ipAddress: new RegExp (<<the_ip>>)
});

However, while debugging my app, I realized that the above query matches and finds anything that has the_ip and not just the exact the_ip

Eg. If I have two documents that have IPs as 1.2.2.2 and 1.2.2.22 and I search for regexp 1.2.2.2, I've noticed that it always matches and returns 1.2.2.22. I feel this is expected since technically the regexp is doing it's job.

However this is not the desired outcome. How do I do a full exact IP match?

Thanks.

I think you need to do two things:

  1. Add delimiters to the IP address
  2. Escape dots in the address

For (1) do:

(^|,)<<the_ip>>(,|$)

That requires that IP is preceded by the ( ^ ) assertion at the beginning of the string or a comma and that IP is followed by a comma or the ( $ ) assertion at the end of the string.

For (2) substitute dots by \\. in the IP string.

"1.2.3.4".replace(/\./g, "\\.")

Dot in regexp means 'any character but new line', so if you don't replace it, you may accidentally match some invalid strings (eg 1a1a1a1 ).

Demo

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