1

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);

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);

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.

conandor
  • 3,637
  • 6
  • 29
  • 36
  • 1
    Well, don't change working code to non-working code. Why do you want to make `$a` a string? – cjm Mar 05 '12 at 07:25

1 Answers1

5

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

insert ($object, $options?)

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.

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800