在MongoDB中,插入操作用于在集合中添加新文档。如果集合不存在,则插入操作将通过插入文档来创建集合。或者,如果该集合存在,则插入操作将在现有集合中添加新文档。 db.collection.insertMany()
方法在集合中插入多个文档。
insertMany()
是一个mongo shell方法,可以插入多个文档。此方法可用于多文档交易中。使用此方法,您可以在具有或不具有_id字段的集合中添加文档。如果添加不带_id字段的文档,则mongodb将为每个文档自动添加_id字段并为它们分配唯一的ObjectId
。默认情况下,此方法按顺序插入文档。
Syntax:
Parameters:
Document: It represents the array of the documents that will insert in the collection.
Optional Parameters:
- writeConcern: It is only used when you do not want to use the default write concern,
- order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.
例子:
在以下示例中,我们正在使用:
db.collection.insertMany(
[ , , ... ],
{
writeConcern: ,
order:
}
)
插入多个不带_id字段的文档:
db.collection.insertMany()
方法将多个文档插入不带_id字段的学生集合中。
插入带有字段的多个文档:
db.collection.insertMany()
方法在具有_id字段的学生集合中插入多个文档。