2

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.

2
  • 2
    try to add delimiters to the ip address (^|,)<<the_ip>>(,|$) Commented Feb 23, 2018 at 12:32
  • 3
    many IPs that are separated by comma - a better option would be to use an array and $elemMatch to find a specific IP. Commented Feb 23, 2018 at 12:49

1 Answer 1

4

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 (e.g. 1a1a1a1).

Demo

Sign up to request clarification or add additional context in comments.

10 Comments

This works. However, is there any specific reason I need to escape the dots?
This won't match in this particular case, which is what is shown in the question: regex101.com/r/sOeD9E/3
But the question is not about searching in a JSON string, but in mongo document. It needs to match in a field that has IPs separated by commas, with a special case of handling beginning and end of the string. The data you use in the example is not correct.
If that is the case then I’m confused why the OP would show that in question. Regardless of that I’m not sure your regex would match anyway (not at computer so unfortunately can’t test). If I’m wrong about that then apologies.
It's looking inside a field named ipAddress not whole document. Read question carefully @l'L'l
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.