duanfu1873 2015-02-16 08:51
浏览 246
已采纳

从mongo shell获取MongoBinData值

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?

  • 写回答

1条回答 默认 最新

  • duancheng3342 2015-06-28 12:05
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败