gpt4 book ai didi

php - 从 mongo shell 获取 MongoBinData 值

转载 作者:IT老高 更新时间:2023-10-28 13:16:10 26 4
gpt4 key购买 nike

我在mongo中保存IP

$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 中的 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 , 存储 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

关于php - 从 mongo shell 获取 MongoBinData 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28537599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com