【问题标题】:function to print document in json format (mongodb)以json格式打印文档的功能(mongodb)
【发布时间】:2013-08-08 23:23:42
【问题描述】:

您好,我正在使用 perl 查询 mongodb,当我返回光标时,如何以 json 格式打印文档

{ "_id" : ObjectId("51fdbfefb12a69cd35000502"), "biography" : "Colombian pop singer, born on February 2, 1977 to a Colombian mother of Spanish-Italian descent and an American father of Lebanese-Italian descent. Shakira is known for a high IQ and is fluent in Spanish, English, Italian and Portuguese.\r\rWriting songs and belly-dancing since childhood, her first album was released when she was a mere 14 years old. Other Spanish-language albums followed, each faring better than its predecessor, but it was not until 2001 that she achieved a world-wide breakthrough with the English-language \"Laundry Service\" album.\r", "imguri" : "http://api.discogs.com/image/A-5530-1218936486.jpeg", "index" : "shakira", "name" : "Shakira", "ready" : "yes", "requests" : "0"}

我在 mongoDB 模块中没有看到任何函数,所以我可能会尝试这样的方法

run_command({printjson => $foo});

但它说 printjson 不是函数

我能做什么

谢谢

【问题讨论】:

  • 您想在哪里打印?控制台?

标签: json perl mongodb


【解决方案1】:

当您找到时,perl 驱动程序将返回一个光标:

my $cursor = $collection->find({ i => { '$gt' => 42 } });

您可以通过以下方式迭代此 $cursor 以获取文档:

while (my $object = $cursor->next) {
    ...
}

在while循环中,你可以访问每个$object的每个字段:

print $object->{i};

如果需要,您也可以将它们转换为 JSON,但为此您需要安装 JSON CPAN module。在 Debian/Ubuntu 上,您可以使用 apt-get install libperl-json,但将 use JSON; 添加到脚本的开头。安装后,您可以输入您的 while 子句:

while (my $object = $cursor->next) {
    my $json = encode_json $object;
    print "$json\n";
}

【讨论】:

  • 谢谢,但我收到此错误,但我收到此错误:既未启用 allow_blessed 也未启用 convert_blessed 设置
  • nvm 找到了我的第二个问题的解决方案,感谢stackoverflow.com/questions/4185482/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 2020-06-15
相关资源
最近更新 更多