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.

1
  • 1
    Well, don't change working code to non-working code. Why do you want to make $a a string? Commented Mar 5, 2012 at 7:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.