English | 简体中文 | 繁體中文
查询

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

「 获取在执行MongoDB写操作后插入的文档数量 」


函数名称:MongoDB\Driver\WriteResult::getInsertedCount() 适用版本:PHP 5 >= 5.6.0, PHP 7, PHP 8

函数描述:该函数用于获取在执行MongoDB写操作后插入的文档数量。

用法: MongoDB\Driver\WriteResult::getInsertedCount(): int

参数:无

返回值:返回一个整数,表示插入的文档数量。

示例:

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

// 定义插入操作
$bulk = new MongoDB\Driver\BulkWrite;
$document1 = ['name' => 'John Doe', 'age' => 30];
$document2 = ['name' => 'Jane Smith', 'age' => 25];
$bulk->insert($document1);
$bulk->insert($document2);

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

// 获取插入的文档数量
$insertedCount = $result->getInsertedCount();
echo "Inserted documents: " . $insertedCount;
?>

输出:

Inserted documents: 2

以上示例演示了如何使用MongoDB\Driver\WriteResult::getInsertedCount()函数获取插入的文档数量。首先,我们连接到MongoDB数据库,然后使用MongoDB\Driver\BulkWrite类定义插入操作。我们插入了两个文档,并执行了插入操作。最后,我们使用getInsertedCount()函数获取插入的文档数量,并将其输出到屏幕上。在这个示例中,插入了两个文档,所以输出结果是Inserted documents: 2

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