MongoDB network subnet lookup

mongodb

Solution

Remember that IPs are just `int`s and subnet masks are just ranges of `int`s - they're displayed as they are so that humans can read them (among other reasons). What I would do is add two additional fields to my MongoDB schema: `startAddr` and `endAddr`. Represent them as `int`s and they will be the starting and ending addresses for your subnet.

Next, you can convert the IP to an `int` in your application. See here for information on converting an IP to an integer, you didn't mention what language you're writing your application in so can't help you there.

Finally, query MongoDB on the following

db.collection.find({startAddr: {$lte: <ip>}, {endAddr: {$gte: <ip>}}})

You can also combine this new schema with some application level code to easily do things like find documents that have overlapping subnets if you need to do that.

Problem

Let's say we have a collection of documents where each document represents a network subnet like this: ``` {'network':'10.0.0.0/24,'someattr':'aaa'} {'network':'192.168.0.0/16','someattr':'bbb'} {'network':'172.16.0.0/16','someattr':'ccc'} ``` Is there any way I can lookup a single ip address (e.g. '10.0.100.50') in the MongoDB collection and identify the subnet/document it belongs to?

Original source