【问题标题】:What is the equivalent of collection.save() in PHP?PHP中collection.save()的等价物是什么?
【发布时间】:2021-11-29 00:15:06
【问题描述】:

mongo shell 有db.collection.save() 命令,可用于替换现有文档。

PHP 中的等价物是什么?

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    您正在 PHP MongoDB 库中查找 MongoDB\Collection::updateOne

    但是,您需要将upsert 选项设置为true,这将模拟db.collection.save() 的“如果存在则更新,如果不存在则创建”行为。

    来自MongoDB's PHP Library Manual 的一些示例代码(很好的资源):

    <?php
    
    $collection = (new MongoDB\Client)->test->users;
    $collection->drop();
    
    $updateResult = $collection->updateOne(
        ['name' => 'Bob'],
        ['$set' => ['state' => 'ny']],
        ['upsert' => true]
    );
    
    printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
    printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
    printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount());
    
    $upsertedDocument = $collection->findOne([
        '_id' => $updateResult->getUpsertedId(),
    ]);
    
    var_dump($upsertedDocument);
    

    输出:

    Matched 0 document(s)
    Modified 0 document(s)
    Upserted 1 document(s)
    object(MongoDB\Model\BSONDocument)#16 (1) {
      ["storage":"ArrayObject":private]=>
      array(3) {
        ["_id"]=>
        object(MongoDB\BSON\ObjectId)#15 (1) {
          ["oid"]=>
          string(24) "57509c4406d7241dad86e7c3"
        }
        ["name"]=>
        string(3) "Bob"
        ["state"]=>
        string(2) "ny"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 2012-09-14
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多