db.collection.insertOne()

On this page本页内容

Definition定义

db.collection.insertOne()

mongo Shell Method

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. 本页记录了mongo shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。

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

Inserts a document into a collection.将文档插入到集合中。

The insertOne() method has the following syntax:insertOne()方法语法如下所示:

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)
Parameter参数Type类型Description描述
document document A document to insert into the collection.要插入集合的文档。
writeConcern document

Optional.可选。A document expressing the write concern. 表达写入关注的文件。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.要将写关注点用于事务,请参阅事务和写关注点

Returns:返回:A document containing:包含以下内容的文件:
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.如果操作运行时使用写入关注,则布尔值acknowledgedtrue;如果写入关注被禁用,则布尔值acknowledgedfalse
  • A field insertedId with the _id value of the inserted document.字段insertedId与插入文档的_id值匹配。

Behaviors行为

Collection Creation集合创作

If the collection does not exist, then the insertOne() method creates the collection.如果集合不存在,那么insertOne()方法将创建集合。

_id Field字段

If the document does not specify an _id field, then mongod will add the _id field and assign a unique ObjectId for the document before inserting. 如果文档未指定_id字段,则mongod将添加_id字段,并在插入之前为文档指定唯一的ObjectIdMost 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将创建并填充。

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

Explainability解释能力

insertOne() is not compatible with db.collection.explain().db.collection.explain()不兼容。

Use insert() instead.请改用insert()

Error Handling错误处理

On error, db.collection.insertOne() throws either a writeError or writeConcernError exception.出现错误时,db.collection.insertOne()会引发writeErrorwriteConcernError异常。

Transactions事务

db.collection.insertOne() 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 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 Document without Specifying an _id Field在不指定_id字段的情况下插入文档

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

try {
   db.products.insertOne( { item: "card", qty: 15 } );
} catch (e) {
   print (e);
};

The operation returns the following document:该操作将返回以下文档:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("56fc40f9d735c28df206d078")
}

Because the documents did not include _id, mongod creates and adds the _id field and assigns it a unique ObjectId value.由于文档不包含_idmongod创建并添加_id字段,并为其分配唯一的ObjectId值。

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

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

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

try {
   db.products.insertOne( { _id: 10, item: "box", qty: 20 } );
} catch (e) {
   print (e);
}

The operation returns the following:该操作返回以下内容:

{ "acknowledged" : true, "insertedId" : 10 }

Inserting an duplicate value for any key that is part of a unique index, such as _id, throws an exception. 为属于唯一索引的任何键(如_id)插入重复值会引发异常。The following attempts to insert a document with a _id value that already exists:以下尝试插入具有已存在的_id值的文档:

try {
   db.products.insertOne( { _id: 10, "item" : "packing peanuts", "qty" : 200 } );
} catch (e) {
   print (e);
}

Since _id: 10 already exists, the following exception is thrown:由于_id:10已经存在,将引发以下异常:

WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 10.0 }",
   "op" : {
      "_id" : 10,
      "item" : "packing peanuts",
      "qty" : 200
   }
})

Increase Write Concern增加写入关注度

Given a three member replica set, the following operation specifies a w of majority, wtimeout of 100:给定一个由三个成员组成的副本集,以下操作指定w的多数,wtimeout100

try {
   db.products.insertOne(
       { "item": "envelopes", "qty": 100, type: "Self-Sealing" },
       { writeConcern: { w : "majority", wtimeout : 100 } }
   );
} catch (e) {
   print (e);
}

If the acknowledgement takes longer than the wtimeout limit, the following exception is thrown:如果确认时间超过wtimeout限制,则会引发以下异常:

WriteConcernError({
   "code" : 64,
   "errmsg" : "waiting for replication timed out",
   "errInfo" : {
     "wtimeout" : true,
     "writeConcern" : {    // Added in MongoDB 4.4
       "w" : "majority",
       "wtimeout" : 100,
       "provenance" : "getLastErrorDefaults"
     }
   }
})

See also参阅