On this page本页内容
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
命令接受以下字段:
insert | string | |
documents | array | |
ordered | boolean | true , then when an insert of a document fails, return without inserting any remaining documents listed in the inserts array. true ,则当插入文档失败时,返回而不插入inserts 数组中列出的任何剩余文档。false , then when an insert of a document fails, continue to insert the remaining documents. false ,则当插入文档失败时,继续插入其余文档。true . true 。 |
writeConcern | document |
|
bypassDocumentValidation | boolean | insert to bypass document validation during the operation. insert 在操作期间绕过文档验证。 |
comment | any |
|
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
数组中的文档总数必须小于或等于最大块大小。
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
选项的支持,该选项允许您在使用验证规则插入或更新集合中的文档时绕过文档验证。
insert
can be used inside multi-document transactions.insert
可以在多文档事务中使用。
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大小限制),请参阅生产注意事项。
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.从MongoDB 4.4开始,如果事务不是跨分片写入事务,则可以在多文档事务中创建集合和索引。
Specifically, in MongoDB 4.4 and greater, if you specify an insert on a non-existing collection in a transaction, the collection is implicitly created.具体来说,在MongoDB 4.4及更高版本中,如果在事务中指定对不存在的集合的插入,则会隐式创建该集合。
In MongoDB 4.4 and earlier, the operation must be run on an existing collection.在MongoDB 4.4及更早版本中,操作必须在现有集合上运行。
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.要对事务使用写问题,请参阅事务和写问题。
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 }
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 }
bypassDocumentValidation
bypassDocumentValidation
实现插入If schema validation validationActions are set to 如果架构验证validationActions设置为error
, inserts to a collection return errors for documents that violate the schema validation rules. error
,则对集合的插入将返回违反架构验证规则的文档的错误。To insert documents which would violate these rules set 要插入违反这些规则的文档,请设置bypassDocumentValidation: true
.bypassDocumentValidation: true
。
Create the 使用user
collection with a validation rule on the status
fields.status
字段上的验证规则创建user
集合。
The validation rule validates that the status must be "Unknown" or "Incomplete":验证规则验证状态必须为“未知”或“未完成”:
db.createCollection("users", { validator: { status: { $in: [ "Unknown", "Incomplete" ] } } })
Attempt to insert a document which violates the validation rule:尝试插入违反验证规则的文档:
db.runCommand({ insert: "users", documents: [ {user: "123", status: "Active" } ] })
The insert returns a write error message:插入将返回写入错误消息:
{ n: 0, writeErrors: [ { index: 0, code: 121, errInfo: { failingDocumentId: ObjectId('6197a7f2d84e85d1cc90d270'), details: { operatorName: '$in', specifiedAs: { status: { '$in': [Array] } }, reason: 'no matching value found in array', consideredValue: 'Active' } }, errmsg: 'Document failed validation' } ], ok: 1 }
Set 将bypassDocumentValidation : true
and rerun the insert:bypassDocumentValidation
设置为true
,然后重新运行插入:
db.runCommand({ insert: "users", documents: [ {user: "123", status: "Active" } ], bypassDocumentValidation: true })
The operation succeeds.操作成功。
To check for documents that violate schema validation rules, use the 要检查违反模式验证规则的文档,请使用validate
command.validate
命令。
The returned document contains a subset of the following fields:返回的文档包含以下字段的子集:
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.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.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:下表显示了该字段的可能值及其意义:
Provenance | |
---|---|
clientSupplied | |
customDefault | setDefaultRWConcern . setDefaultRWConcern 。 |
getLastErrorDefaults | settings.getLastErrorDefaults field. settings.getLastErrorDefaults 字段。 |
implicitDefault |
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 }" } ] }