从mongo shell获取MongoBinData值

我将IP保存在mongo中

$db = new MongoClient();

$db->selectCollection('test', 'test')->insert([
    'ip'=> new MongoBinData(inet_pton('127.0.0.1'), MongoBinData::BYTE_ARRAY),
]);

蒙哥壳

> db.test.find()
{ "_id" : ObjectId("54e1aeeb84663f3407000030"), "ip" : BinData(2,"BAAAAH8AAAE=") }

如何在mongo shell中获取初始数据?

舍恩

看一下以mongod结尾的内容的十六进制转储,以及您插入的内容,应该可以弄清楚:

$ 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

这表明原始的4个字节最终在mongodb中以另外4个字节为前缀。其原因可以在BSON规范中找到,当存储Binary时,前4个字节将存储它包含的值的长度。

这也暗示了解决方案是什么。经过一番摆弄(我从未使用过mongodb),我最终得到了:

> 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));
    });

这将产生您想要的输出: 127.0.0.1

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章