Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

MongoDB replacing an array

by neilwatson (Priest)
on Aug 25, 2012 at 20:42 UTC ( #989753=perlquestion: print w/replies, xml ) Need Help??
neilwatson has asked for the wisdom of the Perl Monks concerning the following question:


I'm trying to use the Perl MongoDb module to extract a list from mongo, alter the data and replace the original list. The replace operation has gone wrong. I have tried this code:

$col->update( { "host" => $host }, { '$set' => { "timestamp" => [ @new ] } }, { 'multiple' => 1, 'safe' => 1 } ) || die "$!";

This does not seem to work as the list is emptied by the update. What have I done wrong?

Neil Watson

Replies are listed 'Best First'.
Re: MongoDB replacing an array
by Khen1950fx (Canon) on Aug 26, 2012 at 03:17 UTC
    This is just a general idea. You'll probably need to adjust the validation options in order for it to work.
    #!/usr/bin/perl use strict; use warnings; use MongoDB; use DateTime; my $today = DateTime->now; my $stamp = DateTime->now->set( 'timestamp' => $today->day, ); my $database = '/tmp/collection'; $database->update( {'host' => ''}, {'set' => {"timestamp" => 'new'}}, {'multiple' => 1, 'safe' => 1} );

      New quoted without an array '@'? In my original example '@new' is any array.

      Neil Watson

      I can't find any documentation to indicate that there is any sort of validation that happens during an insert or update of a generic column.

      I believe this is correct: $col->update( { "host" => $host }, { '$set' => { "timestamp" => \@new } }, { 'multiple' => 1, 'safe' => 1 } ) || die "$!"; It should be a array ref instead.
Re: MongoDB replacing an array
by Mr. Muskrat (Canon) on Aug 26, 2012 at 17:38 UTC

    I don't use MongoDB so bear with me. Has this sort of update worked before? I ask because it looks like you update timestamps with a DateTime object, not an array, as shown in the MongoDB module's DataTypes documentation section on Dates.

      Timestamp is name of an array in a JSON inside a MongoDB database. I want to replace that entire array with a new one. My backup plan is to empty the array in MongoDB and then insert a new one.

      Neil Watson

        And you're sure that @new is not empty at the point of the insert? Have you tried printing out its contents to be sure?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://989753]
Approved by ww
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2018-12-15 16:23 GMT
Find Nodes?
    Voting Booth?
    How many stories does it take before you've heard them all?

    Results (70 votes). Check out past polls.