相对简单的问题,但不是我找到了一个确切答案的问题 - 让我们说我们已经CPAN了MongoDB驱动程序,设置了一些带有一些数据的数据库,并希望将查找的结果捕获到要在perl脚本中操作的文本字符串。
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;
my $conn = MongoDB::Connection->new;
my $db = $conn->test;
my $users = $db->x;
my $parseable;
#Ran this in mongoshell earlier: db.x.insert({"x":82})
$string = $users->find({"x" => 82});
@objects = $string->all;
print "LEN: ".(@objects.length())."\n"; #returns 1....hmmmm...would imply it has my
entry!
print @objects[0]."\n";
print $objects[0]."\n";
print keys(@objects)."\n";
print keys(@objects[0])."\n";
print "@objects[0]"."\n";
这些在命令行输出以下内容,其中没有一个是我想要的) - =:
LEN: 1
HASH(0x2d48584)
HASH(0x2d48584)
1
2
HASH(0x2d48584)
我想要的是将BSON作为字符串 - 我希望mongoshell只返回Perl中的字符串!我的梦想输出如下:
{ "_id" : ObjectId("4fcd1f450a121808f4d78bd6"), "x" : 82 }
随着进一步增加的事实,我可以捕获这个字符串IN A VARIABLE来操纵。
下面的代码会显示正常的东西,但不会把它抓到变量进行操作,最不幸的是:
#!/usr/bin/perl
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;
my $conn = MongoDB::Connection->new;
my $db = $conn->test;
my $users = $db->x;
my $parseable;
#Ran this in mongoshell earlier: db.x.insert({"x":82})
$string = $users->find({"x" => 82});
use Data::Dumper; # new import
print Dumper $string->all,0; # call Dumper method
输出:
$VAR1 = {
'_id' => bless( {
'value' => '4fcd1f450a121808f4d78bd6'
}, 'MongoDB::OID' ),
'x' => '82'
};
有人知道怎么做吗?
谢谢!
答案 0 :(得分:2)
请尝试以下代码:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use MongoDB;
use MongoDB::Collection;
my $conn = new MongoDB::Connection;
my $db = $conn->test;
my $coll = $db->x;
my $all = $coll->find();
my $dts = $all->next;
use Data::Dumper;
print Dumper $dts;
Data::Dumper
是打印复杂Perl数据结构的必备模块。您将了解数据如何以这种方式构建。
然后您可以直接访问键/值:
#!/usr/bin/perl
use strict;
use warnings;
use MongoDB;
use MongoDB::Collection;
my $conn = new MongoDB::Connection;
my $db = $conn->test;
my $coll = $db->x;
my $all = $coll->find();
my $dts = $all->next;
my @a = keys %$dts;
my $str = '{ "' .
$a[0] .
'" : ObjectId("' .
$dts->{_id}. '"), "'.
$a[1].'" : ' .
$dts->{x} .
" }\n";
print $str;
输出
{ "_id" : ObjectId("4fcd248f8fa57d73410ec967"), "x" : 82 }