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?
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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With