在MongoDB中,有两种方法可以用来插入多个文档:批量插入和多个插入。
批量插入使用Bulk.insert
方法,它可以一次插入多个文档。以下是使用批量插入的示例代码:
const MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017', function(err, client) { if (err) throw err; const db = client.db('mydb'); const collection = db.collection('mycollection'); const documents = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Bob', age: 35 } ]; collection.bulkWrite(documents.map(doc => ({ insertOne: { document: doc } })), function(err, result) { if (err) throw err; console.log('Documents inserted:', result.insertedCount); client.close(); }); });
多个插入使用insert
方法和插入多个文档的数组。以下是使用多个插入的示例代码:
const MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017', function(err, client) { if (err) throw err; const db = client.db('mydb'); const collection = db.collection('mycollection'); const documents = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Bob', age: 35 } ]; collection.insert(documents, function(err, result) { if (err) throw err; console.log('Documents inserted:', result.insertedCount); client.close(); }); });
无论是批量插入还是多个插入,都可以用来一次性插入多个文档到MongoDB中。具体使用哪种方法取决于您的需求和个人偏好。