以json格式打印文档的功能(mongodb)

时间:2013-08-07 14:17:22

标签: json perl mongodb

您好我正在使用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不是函数

我能做什么

由于

1 个答案:

答案 0 :(得分:3)

当你找到时,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";
}