Perl 和 MongoDB:返回 find 结果在字符串中



相对简单的问题,但我还没有找到确切的答案 - 假设我们已经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 }

还有一个额外的事实,我可以在变量中捕获这个字符串来操作。

下面的代码可以很好地显示内容,但不会将其抓取到变量中进行操作,最不幸的是:

#!/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'
    };

有人知道如何做到这一点吗?

谢谢!

尝试以下代码:

#!/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 }

最新更新