在MongoDB中,可以使用insertMany()
方法批量写入数据。以下是一个示例:
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/mydb'; MongoClient.connect(url, function(err, db) { if (err) throw err; var collection = db.collection('mycollection'); var documents = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Dave', age: 35 } ]; collection.insertMany(documents, function(err, result) { if (err) throw err; console.log(result.insertedCount + ' documents inserted'); db.close(); }); });
在上面的示例中,我们首先连接到MongoDB数据库,然后获取到集合mycollection
。然后,我们定义了一个包含多个文档的数组documents
,每个文档都包含name
和age
字段。接下来,我们使用insertMany()
方法将这个数组插入到集合中。
一旦数据插入完成,回调函数将返回一个结果对象,其中包含插入的文档数量。最后,我们关闭数据库连接。
请注意,insertMany()
方法是在MongoDB 3.2版本中引入的,如果你使用的是旧版本的MongoDB,你可以考虑使用insert()
方法进行单个文档的插入。