Get MongoBinData value from mongo shell

I save the IP address 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 source data in mongo shell?

+8
php mongodb
source share
1 answer

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

+5
source share

All Articles