查询

MongoDB\Driver\WriteResult::getUpsertedCount()函数—用法及示例

「 获取在执行写操作(如插入或更新)期间插入的文档数量 」


函数名称:MongoDB\Driver\WriteResult::getUpsertedCount()

函数描述:该函数用于获取在执行写操作(如插入或更新)期间插入的文档数量。

适用版本:MongoDB PHP扩展版本1.0.0及以上

用法:

public function getUpsertedCount(): int

参数:无

返回值:返回一个整数,表示在执行写操作期间插入的文档数量。

示例:

<?php
// 创建一个MongoDB连接
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

// 创建写操作对象
$bulk = new MongoDB\Driver\BulkWrite;

// 插入文档
$document1 = ['_id' => 1, 'name' => 'John'];
$bulk->insert($document1);

// 更新文档
$document2 = ['_id' => 2, 'name' => 'Alice'];
$bulk->update(['_id' => 2], ['$set' => $document2], ['upsert' => true]);

// 执行写操作
$result = $manager->executeBulkWrite('database.collection', $bulk);

// 获取插入的文档数量
$upsertedCount = $result->getUpsertedCount();
echo "插入的文档数量:" . $upsertedCount;
?>

在上述示例中,我们首先创建了一个MongoDB连接,然后使用BulkWrite对象进行写操作。在写操作中,我们插入了一个文档和更新了另一个文档。然后,我们执行了写操作并通过$result->getUpsertedCount()获取插入的文档数量。最后,我们将插入的文档数量打印到屏幕上。

请注意,如果没有插入任何文档,该函数将返回0。

补充纠错
热门PHP函数
分享链接