简体   繁体   中英

can't get data from mongodb using perl (get undefined value)

I am trying to get data from mongodb using perl, but I get undefined value for variable $people

my $client = MongoDB::MongoClient->new(host => 
'mongodb://xxx.xxx.xxx.xxx',port=>27017, username => 'xxxx', 
password => 'xxxx');
my $db = $client->get_database("xxx");
my $collection = $db->get_collection("xxx");
my $people = $collection->find_one({"transactionid" => $id});
while (my $p = $people->next) {
    print Dumper $p;
} 

and I want to get this data :

{
    "_id" : ObjectId("5c453500e2fb4adc98e9fa84"),
    "transactionid" : NumberLong(45282),
    "transactionbillerid" : NumberLong(43137),
    "requesttime" : ISODate("2019-01-21T02:57:04.923Z"),
    "requestmessage" : "xxxxxxxx",
    "responsetime" : ISODate("2019-01-21T02:57:05.236Z"),
    "responsemessage" : "xxx"
}

any suggestions, is there something wrong with my code ?

I think you're misunderstanding the value returned by find_one() . There's a big clue in the name, but find_one() returns a single record, not an iterator.

Obviously, I don't have access to your data, so I can't confirm this, but I expect you'll get what you want by running this code:

my $client = MongoDB::MongoClient->new(
  host     => 'mongodb://xxx.xxx.xxx.xxx',
  port     => 27017,
  username => 'xxxx', 
  password => 'xxxx',
);

my $db = $client->get_database("xxx");
my $collection = $db->get_collection("xxx");

my $person = $collection->find_one({"transactionid" => $id});
print Dumper $person;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM