perl MongoDB batch_insert - can be done as an upsert? -


perl, mongodb 2.4.9, perl mongodb 0.702.1

when execute $collection->batch_insert(\@array), works fine, there way make upsert in case?

i'm not sure why want that. if have existing documents on match criteria, you'll destructively overwrite them.

nevertheless, v1.0.0 or later driver (and version 2.6 or later mongod), if add oids ahead of time, can this:

use v5.10; use strict; use warnings; use mongodb; use mongodb::oid;  $mc   = mongodb->connect; $coll = $mc->ns("test.foo"); $coll->drop;  @docs = map { { _id => mongodb::oid->new, x => $_ } } 1 .. 10;  # insert half normal $res = $coll->insert_many( [ map { $docs[ 2 * $_ + 1 ] } 0 .. 4 ] ); "inserted " . $res->inserted_count . " docs";  # upsert whole batch $res = $coll->bulk_write( [     map { ( replace_one => [ { _id => $_->{_id} }, $_, { upsert => 1 } ] ) }     @docs ] );  "matched " . $res->matched_count . " docs"; "upserted " . $res->upserted_count . " docs"; 

when run that, get:

inserted 5 docs matched 5 docs upserted 5 docs 

Comments