Definition定义
insertTheinsertcommand inserts one or more documents and returns a document containing the status of all inserts. The insert methods provided by the MongoDB drivers use this command internally.insert命令插入一个或多个文档,并返回一个包含所有插入状态的文档。MongoDB驱动程序提供的插入方法在内部使用此命令。Tip
In在mongosh, this command can also be run through thedb.collection.insertOne()anddb.collection.insertMany()helper methods.mongosh中,此命令也可以通过db.collection.insertOne()和db.collection.insertMany()辅助方法运行。Helper methods are convenient for助手方法对mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。如果不需要便利性或需要额外的返回字段,请使用database命令。Returns:返回:A document that contains the status of the operation. See Output for details.包含操作状态的文档。详见输出。
Compatibility兼容性
This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Syntax语法
The command has the following syntax:该命令具有以下语法:
db.runCommand(
{
insert: <collection>,
documents: [ <document>, <document>, <document>, ... ],
ordered: <boolean>,
maxTimeMS: <integer>,
writeConcern: { <write concern> },
bypassDocumentValidation: <boolean>,
comment: <any>
}
)Command Fields命令字段
The command takes the following fields:该命令包含以下字段:
insert | ||
documents | ||
ordered | 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. Defaults to true.false,则当插入文档失败时,继续插入其余文档。默认为true。 | |
maxTimeMS |
| |
writeConcern |
| |
bypassDocumentValidation | insert to bypass schema validation during the operation. This lets you insert documents that do not meet the validation requirements.insert以在操作期间绕过架构验证。这允许您插入不符合验证要求的文档。 | |
comment |
|
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数组中的文档总数必须小于或等于最大批量大小。
Schema Validation模式验证
The insert command adds support for the bypassDocumentValidation option, which lets you bypass schema validation when inserting or updating documents in a collection with validation rules.insert命令添加了对bypassDocumentValidation选项的支持,该选项允许您在使用验证规则在集合中插入或更新文档时绕过模式验证。
Transactions事务
insert can be used inside distributed transactions.insert可以在分布式事务中使用。
Important
In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed 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 distributed transactions.也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),另请参阅生产注意事项。
Collection Creation in Transactions事务中的集合创建
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.如果分布式事务不是跨分片写入事务,则可以在该事务内创建集合和索引。
If you specify an insert on a non-existing collection in a transaction, MongoDB creates the collection implicitly.如果在事务中不存在的集合上指定插入,MongoDB将隐式创建该集合。
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.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写关注。
Insert Inaccuracies插入不准确之处
Even if you encounter a server error during an insert, some documents may have been inserted.即使在插入过程中遇到服务器错误,也可能插入了某些文档。
After a successful insert, the system returns 成功插入后,系统返回insert.n, the number of documents inserted into the collection. insert.n,即插入集合的文档数。If the insert operation is interrupted by a replica set state change, the system may continue inserting documents. As a result, 如果插入操作因副本集状态更改而中断,系统可以继续插入文档。因此,insert.n may report fewer documents than actually inserted.insert.n报告的文档可能比实际插入的文档少。
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 }Using Insert with bypassDocumentValidation配合bypassDocumentValidation使用插入
bypassDocumentValidationIf schema validation validationActions are set to 如果模式验证error, inserts to a collection return errors for documents that violate the schema validation rules. validationActions设置为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命令。
Output输出
The returned document contains a subset of the following fields:返回的文档包含以下字段的子集:
insert.okThe status of the command.命令的状态。
insert.nThe number of documents inserted.插入的文档数量。
insert.writeErrorsAn array of documents that contains information regarding any error encountered during the insert operation. The一组文档,其中包含有关插入操作期间遇到的任何错误的信息。writeErrorsarray contains an error document for each insert that errors.writeErrors数组包含每个插入错误的错误文档。Each error document contains the following fields:每个错误文档包含以下字段:insert.writeErrors.indexAn integer that identifies the document in the一个整数,用于标识documentsarray, which uses a zero-based index.documents数组中的文档,该数组使用从零开始的索引。
insert.writeErrors.codeAn integer value identifying the error.标识错误的整数值。
insert.writeErrors.errmsgA description of the error.错误的描述。
insert.writeConcernErrorDocument describing errors that relate to the write concern.描述与写入关注相关的错误的文档。Changed in version 7.0.6.在版本7.0.6中的更改。 (also available in 6.0.14 and 5.0.30也可在6.0.14和5.0.30中使用):When当在insertexecutes onmongos, write concern errors are always reported, even when one or more write errors occur.mongos上执行insert时,即使出现一个或多个写入错误,也总是会报告写入关注错误。In previous releases, the occurrence of write errors could cause the在以前的版本中,写入错误的发生可能会导致insertto not report write concern errors.insert不报告写入关注错误。ThewriteConcernErrordocuments contain the following fields:writeConcernError文档包含以下字段:insert.writeConcernError.codeAn integer value identifying the cause of the write concern error.一个整数值,用于标识写入关注错误的原因。
insert.writeConcernError.errmsgA description of the cause of the write concern error.写入关注错误原因的描述。
insert.writeConcernError.errInfo.writeConcernThe 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.provenanceA string value indicating where the write concern originated (known as write concern一个字符串值,指示写关注的来源(称为写关注provenance). The following table shows the possible values for this field and their significance:provenance(来源))。下表显示了此字段的可能值及其意义:Provenance来源Description描述clientSuppliedThe write concern was specified in the application.应用程序中指定了写入关注。customDefaultThe write concern originated from a custom defined default value.写入关注源于自定义的默认值。See请参阅setDefaultRWConcern.setDefaultRWConcern。getLastErrorDefaultsThe write concern originated from the replica set's写入关注源于副本集的settings.getLastErrorDefaultsfield.settings.getLastErrorDefaults字段。implicitDefaultThe 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 }"
}
]
}