【问题标题】:perl MongoDB batch_insert - can be done as an upsert?perl MongoDB batch_insert - 可以作为 upsert 完成吗?
【发布时间】:2016-07-21 20:15:37
【问题描述】:

perl、mongodb 2.4.9、perl MongoDB 0.702.1

当我执行 $collection->batch_insert(\@array), 它工作正常,但是在这种情况下有什么办法可以做 upsert 吗?

【问题讨论】:

    标签: mongodb perl batch-insert


    【解决方案1】:

    我不确定你为什么要这样做。如果您有符合匹配标准的现有文档,您将破坏性地覆盖它们。

    不过,对于 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
    

    【讨论】:

    • 我知道您使用的是较旧的服务器和驱动程序版本。希望这会给您一些升级的动力。 v1.0.0+ 驱动程序将适用于 mongod 2.4.9 并且上面的代码实际上应该可以工作,只是效率不高,因为它将执行单独的更新操作(10 次往返),而不是将其批处理为单个往返它适用于 mongod 2.6+。
    猜你喜欢
    • 2020-11-25
    • 2019-01-26
    • 1970-01-01
    • 2010-10-18
    • 2021-06-24
    • 2012-11-15
    • 2011-09-13
    • 2011-03-20
    相关资源
    最近更新 更多