本文介绍了用perl插入mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,将项目插入 mongodb

I wrote a script to insert items into mongodb

#!/usr/bin/perl
use strict;
use warnings;
use MongoDB;
use Data::Dumper;

my $hostname = "localhost";
my $port = 27017;

my $conn = MongoDB::Connection->new( "host" => "$hostname",
                                     "port" => $port );
my $db = $conn->test;
my $user_stats = $db->test_stats;

# Insert line
$user_stats->insert({'user_id' => 123,
                     'pointA'=> 12,
                     'pointB' => 13,
                     'total' => 25, } );

my $myStr = $user_stats->find_one();
print Dumper($myStr);

代码运行良好.但是,当我将insert line更改为

The code work well.However when I change to insert line to

my $a = "{'user_id' => 123,
          'pointA' => 12,
          'pointB' => 13,
          'total' => 25}";

$user_stats->insert($a);

由于返回错误而无法正常工作:not a reference at /usr/local/lib/perl5/site_perl/5.12.3/sun4-solaris/MongoDB/Collection.pm line 296.

It doesn't work given back error:not a reference at /usr/local/lib/perl5/site_perl/5.12.3/sun4-solaris/MongoDB/Collection.pm line 296.

推荐答案

上的24object,_%24options?%29> insert方法需要哈希引用:

The insert method on MongoDB::Collection expects a hash-ref:

将给定的$object插入数据库并返回其id值. $object可以是哈希引用,对具有偶数个元素的数组的引用或Tie::IxHash.

Inserts the given $object into the database and returns it's id value. $object can be a hash reference, a reference to an array with an even number of elements, or a Tie::IxHash.

因此,通常的方法是使用哈希引用,而您的$a是字符串,而不是哈希引用.其他选项是可以很容易地投射"到哈希引用(即格式为[key, value, key, value, ...])或(这是维护顺序的哈希);您的$a字符串也不是其中之一.

So, the usual approach is to use a hash-ref and your $a is a string, not a hash-ref. The other options are an array-ref that can be easily "cast" to a hash-ref (i.e. it has the form [key, value, key, value, ...]) or a Tie::IxHash (which is a hash that maintains order); your $a string isn't one of those either.

这篇关于用perl插入mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:45