1

Hi I'm using perl to query mongodb, when I get back a cursor how can I print the documents in json format

{ "_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"}

I dont see any function in the mongoDB module so I migh try something like this

run_command({printjson => $foo});

but It says printjson is not a function

what can I do

Thanks

user2661048
  • 277
  • 1
  • 3
  • 10

1 Answers1

3

The perl driver will return a cursor when you do find:

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

You can iterator over this $cursor to obtain the documents, by doing this:

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

In the while loop, you can then access each field of each $object:

print $object->{i};

If you want, you can also convert them to JSON, but for that you need to have the JSON CPAN module installed. On Debian/Ubuntu, you can use apt-get install libperl-json for that, but add use JSON; to the start of your script. With this installed, you can put in your while clause:

while (my $object = $cursor->next) {
    my $json = encode_json $object;
    print "$json\n";
}
friedo
  • 65,762
  • 16
  • 114
  • 184
Derick
  • 35,169
  • 5
  • 76
  • 99
  • Thanks but I get this error but I get this error: neither allow_blessed nor convert_blessed settings are enabled – user2661048 Aug 07 '13 at 14:54
  • nvm found the solution to my second problem thanks http://stackoverflow.com/questions/4185482/how-to-convert-perl-objects-into-json-and-vice-versa – user2661048 Aug 07 '13 at 15:01