【问题标题】:How to get returned data from mongoDB in Perl?如何在 Perl 中从 mongoDB 获取返回的数据?
【发布时间】:2012-12-30 04:58:37
【问题描述】:

我阅读了http://api.mongodb.org/perl/current/MongoDB/Examples.html,似乎只是 mongoDB 在 Perl 上的文档。如何在 perl 中从 mongoDB 获取查询结果。让我们说成哈希。到目前为止,我已成功连接到数据库。我设法在集合中插入。现在如何发出选择查询并将其返回的数据转换为哈希或类似的东西?

更新:

Example of my data
{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "USA"
 "city" : "Boston"
}

{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "USA"
 "city" : "Seattle"
}

{
 "_id" : ObjectId("asdhgajsdghajgh"),
 "country" : "Canada"
 "city" : "Calgary"
}

My code

my $cursor = $my_collection
    ->find({ country => 1 }) 
    ;
while (my $row = $cursor->next) {
    print "$row\n";
}

此代码不会产生任何输出。 我想基本上遍历整个集合并逐个文档阅读。 不知道我做错了什么。我使用了上面的代码。我将 $cur->next 更改为 $cursor->next 我猜这是一个错字。到目前为止,我很感激所有的答案。

【问题讨论】:

  • api.mongodb.org 上的东西已经过时了。你应该看看CPAN。我已经更新了api.mongodb.org 上的 Perl 链接以指向那里。

标签: perl mongodb


【解决方案1】:

这不是官方文档。前往 CPAN:

迭代结果与 DBI 方式非常相似:

use Data::Printer;
use MongoDB;

# no query is performed on initialization!
my $cursor = $collection
    ->find({ active => 1, country => 'Canada' }) # filter "active" records from Canada
    ->sort({ stamp => -1 }) # order by "stamp" attribute, desc.
    ->limit(1000);          # first 1000 records

# query & iterate
while (my $row = $cur->next) {
    # it is 'p', from Data::Printer!
    p $row;
}

【讨论】:

  • 感谢您的回复。我阅读了上面的一些文档,它帮助我理解了如何获得非常简单的结果,就像我的 $some_users = $users->find({"name" => "Joe"});这个例子没有解释 find() 返回数百万个结果时会发生什么?如何遍历这些结果?
  • 抱歉,添加了迭代器示例!
  • 感谢大家的回答。我再次更新了我的问题。你们能检查一下为什么我的代码没有产生任何输出。我猜这是一个非常简单的菜鸟错误。
  • 编辑了答案!糟糕,不是print,而是p!不过,您必须安装Data::Printer。此外,country => 1 将搜索 numeric 值为 1 的 country。在您的情况下它不会返回任何内容。
  • 快速回复谢谢。我终于找到了我要找的东西。我的 $cursor = $my_collection->find;while (my $row = $cursor->next) {print $row->{'country'}} 这有效
猜你喜欢
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 2019-09-29
  • 2015-01-03
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多