Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get MongoBinData value from mongo shell

Tags:

php

mongodb

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?

like image 736
Hett Avatar asked Feb 16 '15 08:02

Hett


People also ask

How do I show DBS in MongoDB?

If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.

How do I select a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I access mongo shell?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.


1 Answers

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

like image 174
Sjon Avatar answered Nov 15 '22 06:11

Sjon