MongoDB collection.insertMany() 方法
MongoDB 是一个流行的 NoSQL 数据库,它使用文档来存储数据,而不是表格。 MongoDB insertMany() 方法是用于向 MongoDB 数据库中插入多个新文档的方法。
语法
MongoDB insertMany() 方法的语法如下所示:
db.collection.insertMany(documents, options)
其中,db.collection 是要插入数据的集合名称,documents 是一个文档数组,表示要插入的多个文档,options 是一个可选参数,用于指定插入选项。
使用场景
insertMany() 方法适用于以下情况:
- 插入多个新的文档到集合中。
- 如果集合不存在,则会自动创建集合。
- 如果集合存在,则会在集合中插入多个新文档。
- 如果集合中已经存在具有相同
_id值的文档,则会插入失败。
示例
下面是使用 insertMany() 方法插入多个文档的示例:
db.users.insertMany([
{ name: "John", age: 30, email: "[email protected]" },
{ name: "Sarah", age: 25, email: "[email protected]" },
{ name: "Bob", age: 40, email: "[email protected]" }
])
这将向 users 集合中插入三个新文档,每个文档都包含 name、age 和 email 三个字段。
下面是使用 insertMany() 方法和选项插入多个文档的示例:
db.users.insertMany(
[
{ name: "John", age: 30, email: "[email protected]" },
{ name: "Sarah", age: 25, email: "[email protected]" },
{ name: "Bob", age: 40, email: "[email protected]" }
],
{ ordered: false }
)
这将向 users 集合中插入三个新文档,并使用 { ordered: false } 选项来指示在插入过程中出现错误时不停止插入。
结论
使用 insertMany() 方法可以很方便地向 MongoDB 数据库中插入多个新文档,包括在集合中插入多个文档。此外,如果集合不存在,则会自动创建集合。如果集合中已经存在具有相同 _id 值的文档,则插入将失败。