1

I am looking several Q&A here to understand the best way to save and perform sorting of an IP in a mongo db but I can't face up a solution. First of all: how can I save an IP? String? Int? Other? Second: Once saved (assume for example that my Ips go to 10.1.0.20 to 10.1.1.255), I have to get the "highest" IP in my DB and increment the new one by 1. How can I do that? I mean, what is the best way to retrieve it? Is it correct to perfrom

this.model.findOne().sort({"staticIp": -1}).exec();
Ashh
  • 44,693
  • 14
  • 105
  • 132
GigiProve
  • 337
  • 1
  • 5
  • 15

2 Answers2

0

I certainly haven't got an complete solution but would saving the ip as an array work? Since an ip would be fairly easy to fit in an array:

var ip = [127,0,0,1];

This way you would be able to sort on the first element, then if the first element is the same you sort on the second and so on until you have them all sorted.

If anyone with more mongodb knowledge could help with this it would be appreciated!

0

(IPv4 only info, see link for IPv6 discussion) So an ip address is worthless without a mask 1-32 in most cases. This gives you info on what subnet the host in question belongs to and allows you to group by subnets (depending on your use case ofc)

now you can store them as a 32bit unsigned int

  • int 134744072 = 8.8.8.8

or as a

  • doted decimal 8.8.8.8

or a binary string

  • 00001000 00001000 00001000 00001000

But an ip address without a mask is like a house number without a street address in most systems. So having the mask you can do a little network math and get all the hosts on the same network segment, and see how many free addresses you have left.

imo, use an unsigned integer is the way to go and then a second integer to store the mask. And then maybe use sorted insertions/deletion.

I'd point you to this good answer here on a similar topic

good luck!