I save IP in mongo
$db = new MongoClient();
$db->selectCollection('test', 'test')->insert([
'ip'=> new MongoBinData(inet_pton('127.0.0.1'), MongoBinData::BYTE_ARRAY),
]);
mongo shell
> db.test.find()
{ "_id" : ObjectId("54e1aeeb84663f3407000030"), "ip" : BinData(2,"BAAAAH8AAAE=") }
how to get initial data in mongo shell?
Looking at the hexdump of what ends up in mongod, versus 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 prefixed by another 4 bytes in mongodb. The reason for this can be found in the BSON spec, when storing a Binary, the first 4 bytes will store the length of the value it contains.
This also hints as to what the solution is; after a little fiddling (I've 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 result in your desired output: 127.0.0.1