http://www.perlmonks.org?node_id=989753

neilwatson has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

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
watson-wilson.ca

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' => '127.0.0.1'}, {'set' => {"timestamp" => 'new'}}, {'multiple' => 1, 'safe' => 1} );

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

      Neil Watson
      watson-wilson.ca

      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
      watson-wilson.ca

        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?