我正在尝试使用MongoDB
运行Perl,但我什么都没得到
use MongoDB;
use Data::Dumper;
my $client = MongoDB::connect("mongodb://admin:admin123@localhost");
my $db = $client->get_database( 'admin' );
my $x = $db->get_collection( 'inventory' );
my $y = $x->find({"item" => "journal"});
print Dumper($y->all);
在mongo
客户端,我得到了这个
mongo -u admin -p admin123 --authenticationDatabase admin
MongoDB shell version: 3.2.15
connecting to: test
Server has startup warnings:
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten]
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-07-08T08:28:16.694-0500 I CONTROL [initandlisten]
> db.inventory.find({})
{ "_id" : ObjectId("5960dec814a535e879221157"), "item" : "journal", "qty" : 26, "size" : { "h" : 17, "w" : 21, "uom" : "cm" }, "status" : "B" }
{ "_id" : ObjectId("5960dec814a535e879221158"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
{ "_id" : ObjectId("5960dec814a535e879221159"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115a"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
{ "_id" : ObjectId("5960dec814a535e87922115b"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
{ "_id" : ObjectId("5960e7bb14a535e87922115c"), "foo" : { "a" : [ 1, 2, 3 ] } }
{ "_id" : ObjectId("5960e87614a535e87922115d"), "foo" : { "a" : [ 2, 3, 4 ] } }
{ "_id" : ObjectId("5960e87c14a535e87922115e"), "foo" : { "a" : [ 5, 3, 4 ] } }
>
答案 0 :(得分:4)
首先,必须始终启动您编写的每个 Perl程序
use strict;
use warnings 'all';
和请使用比$x
和$y
更好的标识符
当它应该是一个类方法时,你将connect
称为一个简单的子例程。变化
my $client = MongoDB::connect("mongodb://admin:admin123@localhost")
到
my $client = MongoDB->connect("mongodb://admin:admin123@localhost")
答案 1 :(得分:1)
您正在查找错误的数据库。实际上在shell中你正在连接到" test"数据库。见:
connecting to: test
并且您永远不会要求切换命名空间,因此这就是数据的位置。
更改为
$client->get_database( 'test' );
并且如上所述,如果您实际编写MongoDB->connect
代替它会好得多,尽管此时类方法区别的实例方法没什么影响。您只是选择了错误的数据库。 " admin"命名空间由驱动程序自动切换以进行身份验证您需要做的就是使用数据所在的真实空间。