Looking at the hexdump of what ends up in mongod, compared to what you insert, should clarify a lot:
$ php -r 'echo inet_pton("127.0.0.1");'|hexdump 0000000 007f 0100 0000004 $ php -r 'echo base64_decode("BAAAAH8AAAE=");'|hexdump 0000000 0004 0000 007f 0100 0000008
This shows that the original 4 bytes end up prefixing another 4 bytes in mongodb. The reason for this can be found in the BSON specification , when saving a binary file, the first 4 bytes will store the length of the value contained in it.
It also indicates what the decision is; after a little grunt (I never used mongodb), I ended up with:
> db.test.find().forEach(function(d){ var h = d.ip.hex(); print( parseInt(h.substr(8,2), 16)+'.' +parseInt(h.substr(10,2), 16)+'.' +parseInt(h.substr(12,2), 16)+'.' +parseInt(h.substr(14,2), 16)); });
This will produce your desired result: 127.0.0.1
Sjon
source share