perl、mongodb 2.4.9、perl MongoDB 0.702.1
を実行すると正常
$collection->batch_insert(\@array)に動作しますが、この場合にアップサートを行う方法はありますか?
perl、mongodb 2.4.9、perl MongoDB 0.702.1
を実行すると正常
$collection->batch_insert(\@array)に動作しますが、この場合にアップサートを行う方法はありますか?
なぜあなたがそれをしたいのか正確にはわかりません。一致基準に既存のドキュメントがある場合は、それらを破壊的に上書きします。
それでも、v1.0.0 以降のドライバー (およびバージョン 2.6 以降の mongod) では、事前に OID を追加すると、次のようなことができます。
use v5.10;
use strict;
use warnings;
use MongoDB;
use MongoDB::OID;
my $mc = MongoDB->connect;
my $coll = $mc->ns("test.foo");
$coll->drop;
my @docs = map { { _id => MongoDB::OID->new, x => $_ } } 1 .. 10;
# insert half as normal
my $res = $coll->insert_many( [ map { $docs[ 2 * $_ + 1 ] } 0 .. 4 ] );
say "Inserted " . $res->inserted_count . " docs";
# upsert whole batch
$res = $coll->bulk_write( [
map { ( replace_one => [ { _id => $_->{_id} }, $_, { upsert => 1 } ] ) }
@docs
] );
say "Matched " . $res->matched_count . " docs";
say "Upserted " . $res->upserted_count . " docs";
それを実行すると、次のようになります。
Inserted 5 docs
Matched 5 docs
Upserted 5 docs