MongoDB:批量插入(Bulk.insert)与多个插入(insert([...]))

   2025-02-20 5700
核心提示:在MongoDB中,有两种方法可以用来插入多个文档:批量插入和多个插入。批量插入使用Bulk.insert方法,它可以一次插入多个文档。以

在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中。具体使用哪种方法取决于您的需求和个人偏好。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言