从 mongo shell 获取 MongoBinData 值
get MongoBinData value from mongo shell
我把IP保存在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=") }
如何在 mongo shell 中获取初始数据?
查看最终出现在 mongod 中的 hexdump,与您插入的内容相比,应该清楚很多:
$ 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 个字节为前缀。原因可以在 the BSON spec 中找到,当存储二进制文件时,前 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
我把IP保存在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=") }
如何在 mongo shell 中获取初始数据?
查看最终出现在 mongod 中的 hexdump,与您插入的内容相比,应该清楚很多:
$ 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 个字节为前缀。原因可以在 the BSON spec 中找到,当存储二进制文件时,前 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