Database Manual / Reference / mongosh Methods / Collections

db.collection.insertOne() (mongosh method方法)

Definition定义

db.collection.insertOne()

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

Returns:返回A document containing: 包含以下内容的文件:
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.如果操作运行时存在写入关注,则acknowledgedtrue的布尔值,如果禁用写入关注,确认为false的布尔值。
  • A field insertedId with the _id value of the inserted document.一个字段insertedId,具有插入文档的_id值。

Compatibility兼容性

This method 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 insertOne() method has the following form:insertOne()方法具有以下形式:

db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)

The insertOne() method takes the following parameters:insertOne()方法接受以下参数:

Parameter参数Type类型Description描述
documentdocument文档A document to insert into the collection.要插入集合的文档。
writeConcerndocument文档

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.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写入关注

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字段,并在插入之前为文档分配一个唯一的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值在集合中必须是唯一的,以避免重复键错误。

Explainability可解释性

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

Error Handling错误处理

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

Schema Validation Errors架构验证错误

If your collection uses schema validation and has validationAction set to error, inserting an invalid document throws a MongoServerError and db.collection.insertOne() fails.如果集合使用模式验证,并且将validationAction设置为error,则插入无效文档会抛出MongoServerErrordb.collection.insertOne()失败。

Transactions事务

db.collection.insertOne() can be used inside distributed transactions.可以在分布式事务中使用。

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.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写关注

Oplog Entries操作日志条目

If a db.collection.insertOne() operation successfully inserts a document, the operation adds an entry on the oplog (operations log). If the operation fails, the operation does not add an entry on the oplog.如果db.collection.insertOne()操作成功插入文档,则该操作会在oplog(操作日志)上添加一个条目。如果操作失败,则操作不会在oplog上添加条目。

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. 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 insertOne() method includes the _id field. The value of _id must be unique within the collection to avoid duplicate key error.在以下示例中,传递给insertOne()方法的文档包含_id字段。_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. The following attempts to insert a document with a _id value that already exists:唯一索引中的任何键(如_id)插入重复值会引发异常。以下尝试插入一个_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:给定一个由三个成员组成的副本集,以下操作指定wmajoritywtimeout100

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

If the acknowledgment 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" : {
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})

Tip