Perl和MongoDB:返回字符串形式的查找结果

Perl和MongoDB:返回字符串形式的查找结果,perl,mongodb,Perl,Mongodb,相对简单的问题,但不是一个我已经找到确切答案的问题——假设我们已经注册了MongoDB驱动程序,用一些数据建立了一个DB,并希望将查找结果捕获到一个文本字符串中,以便在perl脚本中操作 use MongoDB; use MongoDB::Database; use MongoDB::OID; my $conn = MongoDB::Connection->new; my $db = $conn->test; my $users = $db->x; my $parseable;

相对简单的问题,但不是一个我已经找到确切答案的问题——假设我们已经注册了MongoDB驱动程序,用一些数据建立了一个DB,并希望将查找结果捕获到一个文本字符串中,以便在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";
这些命令在命令行上输出以下内容,它们都不是我想要的)-=:

我想要的是作为字符串的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 }

啊-我明白了-屏幕上的输出很好,但我的问题有误导性-我不仅想要漂亮的终端输出-我想要能够将find()结果作为字符串进行操作。Substr、索引等等。所以,在这个特殊的例子中,虽然它输出得很好,但它仍然不能为我将其捕获到字符串中。谢谢你!我将发布此结果以添加到问题中!这是散列引用,不是字符串;)请参见
perldoc perlref
{“\u id”:ObjectId(“4fcd150a12108f4d78bd6”),“x”:82}
是来自
mongo
shell的输出。再次编辑以更好地满足您的需要=)我非常感兴趣的是谁否决了这一点,为什么?这个问题怎么了?
{ "_id" : ObjectId("4fcd248f8fa57d73410ec967"), "x" : 82 }