db.collection.insertOne()
On this page本页内容
Definition定义
db.collection.insertOne()
- Important
mongosh Method
This page documents a
mongosh
method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see the
insert
command.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:Inserts a single document into a collection.在集合中插入单个文档。TheinsertOne()
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
astrue
if the operation ran with write concern orfalse
if write concern was disabled.acknowledged
值为true
;如果写入关注被禁用,则布尔acknowledged
值为false
。A field具有插入文档的insertedId
with the_id
value of the inserted document._id
值的字段insertedId
。
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 大多数驱动程序创建一个ObjectId并插入_id
field, but the mongod
will create and populate the _id
if the driver or application does not._id
字段,但如果驱动程序或应用程序没有创建并填充_id
,mongod
将创建并填充。
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()
引发writeError
或writeConcernError
异常。
Transactions事务
db.collection.insertOne()
can be used inside multi-document transactions.可以在多文档事务中使用。
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.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项。
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及更早版本中,操作必须在现有集合上运行。
See also: 另请参阅:
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
字段
_id
FieldIn 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._id
,mongod
创建并添加_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
字段的文档
_id
FieldIn 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. 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
:w
为majority
,wtimeout
为100
:
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: 另请参阅:
To insert multiple documents, see要插入多个文档,请参阅db.collection.insertMany()
db.collection.insertMany()
WriteResult.writeConcernError