insert

On this page本页内容

Definition定义

insert

The insert command inserts one or more documents and returns a document containing the status of all inserts. insert命令插入一个或多个文档,并返回一个包含所有插入状态的文档。The insert methods provided by the MongoDB drivers use this command internally.MongoDB驱动程序提供的插入方法在内部使用此命令。

The command has the following syntax:此命令语法如下所示:

{
   insert: <collection>,
   documents: [ <document>, <document>, <document>, ... ],
   ordered: <boolean>,
   writeConcern: { <write concern> },
   bypassDocumentValidation: <boolean>,
   comment: <any>
}

The insert command takes the following fields:insert命令包含以下字段:

Field字段Type类型Description描述
insert string The name of the target collection.目标集合的名称。
documents array An array of one or more documents to insert into the named collection.要插入命名集合的一个或多个文档的数组。
ordered boolean Optional.可选。If true, then when an insert of a document fails, return without inserting any remaining documents listed in the inserts array. 如果为true,则当文档插入失败时,返回,而不插入inserts数组中列出的任何剩余文档。If false, then when an insert of a document fails, continue to insert the remaining documents. 如果为false,则当插入文档失败时,继续插入剩余的文档。Defaults to true.默认为true
writeConcern document

Optional.可选。A document that expresses the write concern of the insert command. 表示insert命令的写入问题的文档。Omit to use the default write concern.忽略使用默认的写关注点。

Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点

bypassDocumentValidation boolean

Optional.可选。Enables insert to bypass document validation during the operation. 允许insert在操作过程中绕过文档验证。This lets you insert documents that do not meet the validation requirements.这样可以插入不符合验证要求的文档。

New in version 3.2.版本3.2中的新功能。

comment any

Optional.可选。A user-provided comment to attach to this command. 用户提供了要附加到此命令的注释。Once set, this comment appears alongside records of this command in the following locations:设置后,此注释将与此命令的记录一起出现在以下位置:

A comment can be any valid BSON type (string, integer, object, array, etc).注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

New in version 4.4.版本4.4中的新功能。

Returns:A document that contains the status of the operation. 包含操作状态的文档。See Output for details.有关详细信息,请参阅输出

Behavior行为

Size Limit大小限制

The total size of all the documents array elements must be less than or equal to the maximum BSON document size.所有documents数组元素的总大小必须小于或等于最大BSON文档大小

The total number of documents in the documents array must be less than or equal to the maximum bulk size.documents数组中的文档总数必须小于或等于maximum bulk size

Document Validation文件验证

The insert command adds support for the bypassDocumentValidation option, which lets you bypass document validation when inserting or updating documents in a collection with validation rules.insert命令增加了对bypassDocumentValidation选项的支持,该选项允许在使用验证规则插入或更新集合中的文档时绕过文档验证

Transactions事务

insert can be used inside multi-document transactions.可以在多文档事务中使用insert

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项

Collection Creation in Transactions事务中的集合创建

Starting in MongoDB 4.4 with feature compatibility version (fcv) "4.4", you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.功能兼容版本(fcv)"4.4"的MongoDB 4.4开始,如果事务不是跨切分写入事务,则可以在多文档事务中创建集合和索引。

As such, for feature compatibility version (fcv) "4.4" and greater, if you specify an insert on a non-existing collection in a transaction, the collection is implicitly created.因此,对于功能兼容性版本(fcv)"4.4"及更高版本,如果在事务中对不存在的集合指定插入,则将隐式创建该集合。

If the feature compatibility version (fcv) is "4.2" or less, the operation must be against an existing collection.如果功能兼容版本(fcv)"4.2"或更低,则操作必须针对现有集合。

Write Concerns and Transactions撰写关注事项和交易记录

Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点

Examples示例

Insert a Single Document插入单个文档

Insert a document into the users collection:将文档插入users集合:

db.runCommand(
   {
      insert: "users",
      documents: [ { _id: 1, user: "abc123", status: "A" } ]
   }
)

The returned document shows that the command successfully inserted a document. 返回的文档显示命令已成功插入文档。See Output for details.有关详细信息,请参阅输出

{ "ok" : 1, "n" : 1 }

Bulk Insert批量插入

Insert three documents into the users collection:users集合中插入三个文档:

db.runCommand(
   {
      insert: "users",
      documents: [
         { _id: 2, user: "ijk123", status: "A" },
         { _id: 3, user: "xyz123", status: "P" },
         { _id: 4, user: "mop123", status: "P" }
      ],
      ordered: false,
      writeConcern: { w: "majority", wtimeout: 5000 }
   }
)

The returned document shows that the command successfully inserted the three documents. 返回的文档显示命令成功插入了这三个文档。See Output for details.有关详细信息,请参阅输出

{ "ok" : 1, "n" : 3 }

Output输出

The returned document contains a subset of the following fields:返回的文档包含以下字段的子集:

insert.ok

The status of the command.命令的状态。

insert.n

The number of documents inserted.插入的文档数。

insert.writeErrors

An array of documents that contains information regarding any error encountered during the insert operation. 包含有关插入操作期间遇到的任何错误的信息的文档数组。The writeErrors array contains an error document for each insert that errors.writeErrors数组包含每个插入错误的错误文档。

Each error document contains the following fields:每个错误文档都包含以下字段:

insert.writeErrors.index

An integer that identifies the document in the documents array, which uses a zero-based index.一个整数,用于标识documents数组中的文档,该数组使用从零开始的索引。

insert.writeErrors.code

An integer value identifying the error.标识错误的整数值。

insert.writeErrors.errmsg

A description of the error.对错误的描述。

insert.writeConcernError

Document that describe error related to write concern and contains the field:描述与写入问题相关的错误的文档,包含以下字段:

insert.writeConcernError.code

An integer value identifying the cause of the write concern error.标识写入问题错误原因的整数值。

insert.writeConcernError.errmsg

A description of the cause of the write concern error.对写入问题错误原因的描述。

insert.writeConcernError.errInfo.writeConcern

New in version 4.4.版本4.4中的新功能。

The write concern object used for the corresponding operation. 用于相应操作的写关注点对象。For information on write concern object fields, see Write Concern Specification.有关写入关注点对象字段的信息,请参阅写入关注点规范

The write concern object may also contain the following field, indicating the source of the write concern:写关注点对象还可能包含以下字段,指示写关注点的来源:

insert.writeConcernError.errInfo.writeConcern.provenance

A string value indicating where the write concern originated (known as write concern provenance). 一个字符串值,指示写关注点的来源(称为写关注点provenance)。The following table shows the possible values for this field and their significance:下表显示了该字段的可能值及其重要性:

ProvenanceDescription描述
clientSupplied The write concern was specified in the application.应用程序中指定了写入问题。
customDefault The write concern originated from a custom defined default value. 写入问题源于自定义的默认值。See setDefaultRWConcern.请参阅setDefaultRWConcern
getLastErrorDefaults The write concern originated from the replica set’s settings.getLastErrorDefaults field.写入问题源于副本集的settings.getLastErrorDefaults字段。
implicitDefault The write concern originated from the server in absence of all other write concern specifications.在没有所有其他写关注规范的情况下,写关注源于服务器。

The following is an example document returned for a successful insert of a single document:以下是成功insert单个文档时返回的示例文档:

{ ok: 1, n: 1 }

The following is an example document returned for an insert of two documents that successfully inserted one document but encountered an error with the other document:以下是insert两个文档时返回的示例文档,成功插入了一个文档,但另一个文档出现错误:

{
   "ok" : 1,
   "n" : 1,
   "writeErrors" : [
      {
         "index" : 1,
         "code" : 11000,
         "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.users.$_id_  dup key: { : 1.0 }"
      }
   ]
}