mongodb 批量插入
时间: 2023-07-06 22:33:50 浏览: 47
你可以使用`insertMany()`方法批量插入MongoDB中的文档。这个方法接收一个文档数组作为参数,将这个数组中的所有文档插入到指定的集合中。
下面是一个例子,展示如何使用`insertMany()`方法批量插入文档:
```
const MongoClient = require('mongodb').MongoClient;
// 连接到MongoDB
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
if (err) throw err;
// 选择要操作的数据库
const db = client.db('mydb');
// 选择要操作的集合
const collection = db.collection('mycollection');
// 要插入的文档数组
const docs = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 40 }
];
// 批量插入文档
collection.insertMany(docs, function(err, result) {
if (err) throw err;
console.log(result.insertedCount + ' documents inserted');
client.close();
});
});
```
在上面的例子中,我们连接到MongoDB服务器并选择要操作的数据库和集合。然后,我们定义了一个文档数组,并将其作为参数传递给`insertMany()`方法。
`insertMany()`方法返回一个结果对象,其中包含有关插入操作的信息。在这个例子中,我们打印出插入的文档数量,并关闭与MongoDB的连接。