db.collection.insert()

On this page本页内容

Important重要
Deprecated mongosh Method弃用的mongosh方法

This method is deprecated in mongosh. 这种方法在mongosh中被弃用。For alternative methods, see Compatibility Changes with Legacy mongo Shell.有关其他方法,请参阅与旧mongo Shell的兼容性更改。

Definition定义

db.collection.insert()

Inserts a document or documents into a collection.将一个或多个文档插入到集合中。

The insert() method has the following syntax:insert()方法具有以下语法:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)
Parameter参数Type类型Description描述
documentdocument or arrayA document or array of documents to insert into the collection.要插入到集合中的文档或文档数组。
writeConcerndocument

Optional. 可选。A document expressing the write concern. Omit to use the default write concern. 表示写入关注点的文件。省略以使用默认写入关注点。See 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.要将写关注点用于事务,请参阅事务和写关注点

orderedboolean

Optional. 可选。If true, perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.如果为true,则对数组中的文档执行有序插入,如果其中一个文档发生错误,MongoDB将返回而不处理数组中的其余文档。

If false, perform an unordered insert, and if an error occurs with one of documents, continue processing the remaining documents in the array.如果为false,则执行无序插入,如果其中一个文档出现错误,则继续处理数组中的其余文档。

Defaults to true.默认为true

The insert() returns an object that contains the status of the operation.insert()返回包含操作状态的对象。

Returns:返回:

Behaviors行为

Write Concern写入关注点

The insert() method uses the insert command, which uses the default write concern. insert()方法使用insert命令,该命令使用默认的写入关注点To specify a different write concern, include the write concern in the options parameter.要指定不同的写关注点,请在options参数中包含写关注点。

Create Collection创建集合

If the collection does not exist, then the insert() method will create the collection.如果集合不存在,则insert()方法将创建集合。

_id Field字段

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId() for the document before inserting. 如果文档没有指定_id字段,则MongoDB将在插入之前添加_id字段并为文档分配唯一的ObjectId()Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.大多数驱动程序创建一个ObjectId并插入_id字段,但如果驱动程序或应用程序不创建并填充_idmongod将创建并填充该_id

If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.如果文档包含_id字段,则_id值在集合中必须唯一,以避免重复键错误。

Transactions事务

db.collection.insert() can be used inside multi-document transactions.可以在多文档事务处理中使用。

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, 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及更早版本中,操作必须在现有集合上运行。

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示例

The following examples insert documents into the products collection. 以下示例将文档插入到products集合中。If the collection does not exist, the insert() method creates the collection.如果集合不存在,insert()方法将创建集合。

Insert a Document without Specifying an _id Field插入文档而不指定_id字段

In the following example, the document passed to the insert() method does not contain the _id field:在下面的示例中,传递给insert()方法的文档不包含_id字段:

db.products.insert( { item: "card", qty: 15 } )

During the insert, mongod will create the _id field and assign it a unique ObjectId() value, as verified by the inserted document:在插入过程中,mongod将创建_id字段并为其分配一个唯一的ObjectId()值,该值由插入的文档验证:

{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }

The ObjectId values are specific to the machine and time when the operation is run. As such, your values may differ from those in the example.ObjectId值特定于运行操作的机器和时间。因此,您的值可能与示例中的值不同。

Insert a Document Specifying an _id Field插入指定_id字段的文档

In the following example, the document passed to the insert() method includes the _id field. 在下面的示例中,传递给insert()方法的文档包含_id字段。The value of _id must be unique within the collection to avoid duplicate key error._id的值在集合中必须是唯一的,以避免重复的键错误。

db.products.insert( { _id: 10, item: "box", qty: 20 } )

The operation inserts the following document in the products collection:该操作将在products集合中插入以下文档:

{ "_id" : 10, "item" : "box", "qty" : 20 }

Insert Multiple Documents插入多个文档

The following example performs a bulk insert of three documents by passing an array of documents to the insert() method. 下面的示例通过将一个文档数组传递给insert()方法来执行三个文档的批量插入。By default, MongoDB performs an ordered insert. 默认情况下,MongoDB执行有序插入。With ordered inserts, if an error occurs during an insert of one of the documents, MongoDB returns on error without processing the remaining documents in the array.对于有序插入,如果在插入其中一个文档时发生错误,MongoDB将返回错误,而不处理数组中的其余文档。

The documents in the array do not need to have the same fields. 数组中的文档不需要具有相同的字段。For instance, the first document in the array has an _id field and a type field. 例如,数组中的第一个文档有一个_id字段和一个type字段。Because the second and third documents do not contain an _id field, mongod will create the _id field for the second and third documents during the insert:由于第二个和第三个文档不包含_id字段,mongod将在插入过程中为第二和第三文档创建_id字段:

db.products.insert(
   [
     { _id: 11, item: "pencil", qty: 50, type: "no.2" },
     { item: "pen", qty: 20 },
     { item: "eraser", qty: 25 }
   ]
)

The operation inserted the following three documents:该操作插入了以下三个文档:

{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }

Perform an Unordered Insert执行无序插入

The following example performs an unordered insert of three documents. 以下示例执行三个文档的无序插入。With unordered inserts, if an error occurs during an insert of one of the documents, MongoDB continues to insert the remaining documents in the array.对于无序插入,如果在插入其中一个文档时发生错误,MongoDB将继续在数组中插入其余的文档。

db.products.insert(
   [
     { _id: 20, item: "lamp", qty: 50, type: "desk" },
     { _id: 21, item: "lamp", qty: 20, type: "floor" },
     { _id: 22, item: "bulk", qty: 100 }
   ],
   { ordered: false }
)

Override Default Write Concern覆盖默认写入问题

The following operation to a replica set specifies a write concern of w: 2 with a wtimeout of 5000 milliseconds. 以下对副本集的操作指定了w:2写入关注wtimeout5000毫秒。This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.此操作要么在写入传播到主服务器和一个辅助服务器之后返回,要么在5秒后超时。

db.products.insert(
    { item: "envelopes", qty : 100, type: "Clasp" },
    { writeConcern: { w: 2, wtimeout: 5000 } }
)

WriteResult

When passed a single document, insert() returns a WriteResult object.当传递单个文档时,insert()返回WriteResult对象。

Successful Results成功的结果

The insert() returns a WriteResult() object that contains the status of the operation. insert()返回包含操作状态的WriteResult()对象。Upon success, the WriteResult() object contains information on the number of documents inserted:成功后,WriteResult()对象包含有关插入文档数量的信息:

WriteResult({ "nInserted" : 1 })

Write Concern Errors写入问题错误

If the insert() method encounters write concern errors, the results include the WriteResult.writeConcernError field:如果insert()方法遇到写问题错误,则结果包括WriteResult.writeConcernError字段:

WriteResult({
  "nInserted" : 1,
  "writeConcernError"({
     "code" : 64,
     "errmsg" : "waiting for replication timed out",
     "errInfo" : {
       "wtimeout" : true,
       "writeConcern" : {
    // Added in MongoDB 4.4
         "w" : "majority",
         "wtimeout" : 100,
         "provenance" : "getLastErrorDefaults"
       }
     }
})
Tip提示
See also: 参阅:

Errors Unrelated to Write Concern与写入问题无关的错误

If the insert() method encounters a non-write concern error, the results include the WriteResult.writeError field:如果insert()方法遇到非写入问题错误,则结果包括WriteResult.writeError字段:

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.foo.$_id_  dup key: { : 1.0 }"
   }
})

BulkWriteResult

When passed an array of documents, insert() returns a BulkWriteResult() object. 当传递文档数组时,insert()返回BulkWriteResult()对象。See BulkWriteResult() for details.有关详细信息,请参阅BulkWriteResult()

←  db.collection.hideIndex()db.collection.insertOne() →