0

比較的単純な質問ですが、私が正確な答えを見つけたものではありません。たとえば、MongoDB ドライバーを CPAN 化し、データを使用して 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";

これらはコマンドラインに次のように出力しますが、どれも私が望んでいたものではありません)-=:

LEN: 1
HASH(0x2d48584)
HASH(0x2d48584)
1
2
HASH(0x2d48584)

私が欲しいのは文字列としての BSON です - Perl の文字列で mongoshell が返すものが欲しいのです! 私の夢の出力は次のようになります。

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

誰もこれを行う方法を知っていますか?

ありがとう!

4

1 に答える 1

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 }
于 2012-06-04T21:08:48.747 に答える