Docs 菜单
Docs 主页
/ / /
PHP 库手册
/

插入文档

在此页面上

  • Overview
  • 样本数据
  • _id 字段
  • 插入一个文档
  • 插入多个文档
  • 修改插入行为
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用MongoDB PHP库通过执行插入操作将文档添加到MongoDB集合。

插入操作将一个或多个文档插入MongoDB集合。您可以使用以下方法执行插入操作:

  • MongoDB\Collection::insertOne() 插入单个文档的方法

  • MongoDB\Collection::insertMany() 插入一个或多个文档的方法

本指南中的示例使用 Atlas示例数据集sample_restaurants数据库中的restaurants集合。要从PHP应用程序访问权限此集合,请实例化一个连接到Atlas 集群的MongoDB\Client ,并将以下值分配给$collection变量:

$collection = $client->sample_restaurants->restaurants;

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

在 MongoDB 集合中,每个文档必须包含具有唯一字段值的 _id 字段。

MongoDB 允许您通过两种方式管理该字段:

  • 自行为每个文档设置_id字段,确保每个值都是唯一的。

  • 让驾驶员自动为每个文档_id字段生成唯一的ObjectId值。

除非您可以保证唯一性,否则我们建议让驱动程序自动生成_id值。

注意

重复的_id值违反了唯一索引约束,导致驾驶员返回MongoDB\Driver\Exception\BulkWriteException错误。

要了解有关_id字段的更多信息,请参阅 MongoDB Server 手册中的唯一索引指南。

要了解有关文档结构和规则的更多信息,请参阅 MongoDB Server 手册中的文档指南。

要将单个文档添加到 MongoDB 集合,请调用MongoDB\Collection::insertOne()方法并传递要添加的文档。

以下示例将文档插入restaurants集合:

$result = $collection->insertOne(['name' => 'Mongo\'s Burgers']);

要将多个文档添加到MongoDB集合,请调用MongoDB\Collection::insertMany()方法并传递包含要添加的文档列表的大量。

以下示例将两个文档插入restaurants集合:

$restaurants = [
['name' => 'Mongo\'s Burgers'],
['name' => 'Mongo\'s Pizza']
];
$result = $collection->insertMany($restaurants);

您可以通过将指定选项值的大量作为参数传递来修改MongoDB\Collection::insertOne()MongoDB\Collection::insertMany()方法的行为。下表描述了您可以在大量中设立的一些选项:

字段
说明
bypassDocumentValidation
If set to true, allows the write operation to opt out of document-level validation.
Defaults to false.
Type: bool
writeConcern
Sets the write concern for the operation.
Defaults to the write concern of the namespace.
Type: MongoDB\Driver\WriteConcern
ordered
If set to true, the operation stops inserting documents when one insert fails. If false, the operation continues to insert the remaining documents when one insert fails. You cannot pass this option to the insertOne() method.
Defaults to true.
Type: bool
comment
A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.
Type: any valid BSON type

以下代码使用insertMany()方法将三个新文档插入到集合中。由于选项大量中的bypassDocumentValidation字段设立为true ,因此此插入操作会绕过文档级验证:

$docs = [
['name' => 'Mongo\'s Burgers'],
['name' => 'Mongo\'s Pizza'],
['name' => 'Mongo\'s Tacos']
];
$result = $collection->insertMany($docs, ['bypassDocumentValidation' => true]);

要查看使用MongoDB PHP库插入文档的可运行代码示例,请参阅将数据写入MongoDB。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

Update Documents